2

Is it possible to yield variable in jquery? I want to set a variable in partial views, based on the variable I set a certain menu item as active. I have a menu where I want to yield the active item like this (in my main layout view):

function setMenu(){
    $('#menu-item-'@yield('menu-item', 'home')).addClass('active');
}

unfortunately this isn't valid. Is it possible to yield with blade in jquery?

my current 'fix'

View

@if ($menuItem = 'news') @endif

Layout

setMenu('@if(isset($menuItem)){{ $menuItem }}@endif ');
Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169
  • this will help .. http://stackoverflow.com/questions/13002626/laravels-blade-how-can-i-set-variables-in-a-template – MrPandav Jul 25 '15 at 13:10
  • Why is 'home' hard-coded in your example code? Is this jQuery function only on your home page? If so, you could use '#menu-item-home', so obviously not. The short answer is 'no', you can't use @yield in jQuery obviously. But that's the wrong question -- tell us what you're trying to do, and we can help you do it the correct way. "yield the active item" isn't a thing in jQuery, so can you describe your problem differently? – Ben Claar Jul 25 '15 at 15:15
  • 1
    @Ben if you use yield you can set a default value, in this case home so if i dont set menu-item the value will be home. – Sven van den Boogaart Jul 25 '15 at 15:19
  • Ah yes, forgot about the default value, that makes more sense. – Ben Claar Jul 25 '15 at 15:20
  • @Ben I want to set a variable in partial views, based on the variable I set a certain menu item as active. I have a menu where I want to yield the active item – Sven van den Boogaart Jul 25 '15 at 15:30
  • It seems it's invalid because of jquery wrong syntax... $('#menu-item-'@yield('menu-item', 'home')) will output $('#menu-item-''home')... use @yield inside quantitation => $('#menu-item-@yield("menu-item", "home")') or use + => $('#menu-item-'+@yield('menu-item', 'home')) – Mahdi Rashidi Mar 02 '23 at 12:09

1 Answers1

0

Since you mention @yield, you seem to know the active menu item at render time in PHP.

So I suggest outputting an 'active' class on the active menu item as you output your menu. Something like:

<?php $activeMenuItem = View::yieldContent('menu-item', 'home'); ?>
@foreach ($menuItems as $menuItem)
    <?php $isActive = $menuItem->route === $activeMenuItem ?>
    <li class="{{ $isActive ? 'active' : '' }}">
        {!! link_to_route($menuItem->route, $menuItem->name) !!}
    </li>
@endforeach
Ben Claar
  • 3,285
  • 18
  • 33