Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel blade - Add a class if a condition is met

This is simple but I can't seem to be able to do it with blade and I usually go back to php for this but, since I can't declare a new php variable with blade (without printing it, that is) how should I change a simple class name if a certain condition is met? Take this example of a link, I just want to add the class "active" if $hostess->active=1

 {{ HTML::linkRoute('hostesses.index', 'Archived', $params, array('class' => 'btn btn-default')) }}

I know how to do this with php, but how would it be done with blade?

like image 647
Elaine Marley Avatar asked Apr 30 '14 08:04

Elaine Marley


3 Answers

You could do this:

// App/Http/routes.php
Route::get('foo/bar', 'FooController@bar);
// Your blade file
<li class="{{ Request::path() ==  'foo/bar' ? 'active' : ''  }}">
    <a href="{{ url('foo/bar') }}"></i> Bar</a>
</li>
like image 73
JP Blanco Avatar answered Oct 17 '22 05:10

JP Blanco


Something like this?

{{ HTML::linkRoute('hostesses.index', 'Archived', $params, array('class' => $hostess->active ? 'btn btn-info' : 'btn btn-default')) }}
like image 10
The Alpha Avatar answered Oct 17 '22 05:10

The Alpha


There is also another option:

<li class="@if(Request::is('/')) is-active @endif">
    <a href="{{ route('index') }}">Home</a>
</li>
like image 10
Gucu112 Avatar answered Oct 17 '22 04:10

Gucu112