Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic Active Class For Twitter Bootstrap Navigation in Laravel

Like most people, I'm using Twitter Bootstrap for the site I'm currently developing in Laravel. So far I'm enjoying using Laravel as a PHP equivalent to Rails, but I'm wondering if there's a better way to do the navigation bars. I'm attempting to make sure that my navbar li tags get the active class automatically, so I have this:

<ul class="nav nav-pills">
@if(URL::current() . "/" == URL::route('home'))
    <li class="active">
@else
    <li>
@endif
    <a href="{{ route('home') }}">Home</a>
</li>
@if(URL::current() == URL::route('about'))
    <li class="active">
@else
    <li>
@endif
    <a href="{{ route('about') }}">About</a>
</li>
</ul>

This'll be fine, for now. But when I've got menus, and more navigations it'll end up looking awful to debug and deal with.

Is there anything akin to the Gem Tabulous for Laravel or a generally nicer way to deal with navigation in Laravel?

like image 823
DrugCrazed Avatar asked Jun 24 '13 01:06

DrugCrazed


2 Answers

I use this:

<li class="{{Request::path() == 'home' ? 'active' : '';}}">
  <a href="/home"><i class="fa fa-home"></i>Home</a>
</li>
like image 125
joshdcid Avatar answered Nov 10 '22 05:11

joshdcid


Take a look at the Bootstrapper package, it has lots of tools to help you with Twitter Bootstrap. In your example, you could build the navigation like this:

Navigation::pills(array(
    array(
        'label'  => 'Home',
        'url'    => URL::route('home'),
    ),
    array(
        'label'  => 'About',
        'url'    => URL::route('about'),
    )
));

There's also the shorthand method, less verbose, which I don't particularly like, but can be used:

Navigation::pills(
    Navigation::links(array(
        array('Home', URL::route('home')),
        array('About', URL::route('about')),
    ))
);

It's important to note that in both examples, Bootstrapper takes care of the active class automatically, comparing the current request URL against the one passed to the item. If, however, you wish to specify a different condition for this to apply, simply pass an active value, or a third value in the array, for the shorter method. Example:

Navigation::pills(array(
    array(
        'label'  => 'Home',
        'url'    => URL::route('home'),
    ),
    array(
        'label'  => 'About',
        'url'    => URL::route('about'),
        'active' => true,
    )
));

or

Navigation::pills(
    Navigation::links(array(
        array('Home', URL::route('home')),
        array('About', URL::route('about'), true),
    ))
);
like image 9
rmobis Avatar answered Nov 10 '22 05:11

rmobis