2
votes

Using the package mcamara/laravel-localization in Laravel 5.1 I managed to localize my site and also to translate the routes. The problem is now the following: How can I add a custom class "active" via blade template depending on the current route?

I have tried so far using HTML::macro but it seems the package laravelcollective/html: "5.1.*" isn't fully compatible (especially macros) with L5.1.

Even if I would manage to use an macro I can not use the Request::is('about') because the routes are translated. I'm pretty sure here has to be an easy approach...

Example routes:
www.sitename.com/en/about = www.sitename.com/ro/despre => route to same controller/action
4

4 Answers

3
votes

Try this!

<li class="@if (Request::is('/')) {{'active'}} @endif"><a href="/">Home <span class="sr-only">(current)</span></a></li>    
<li class="@if (Request::is('about')) {{'active'}} @endif"><a href="{{URL::to('/about')}}">About</a></li>
<li class="@if (Request::is('contact')) {{'active'}} @endif"><a href="{{URL::to('/contact')}}">Contact</a></li>
2
votes

With inspiring help from @keithm and from here I did the following:

First extend blade with a new directive, built directly in the AppServiceProvider.php

Blade::directive('activeState', function($expression) {
    return '<?php echo activeClass('. $expression . '); ?>';
});

Then in your helpers file (if you don't have one you can create it into app/Http/helpers.php) add the following

function activeClass($url) {
    return Request::url() == $url ? 'active' : '';
} 

In blade directly use then the following directive:

<a href="{{ URL::route('front.portfolio.index') }}" class="nav-block @activeState(URL::route('front.portfolio.index'))">
0
votes

Not sure if I got your question but is this what you're looking for?

<span class="someClass @if (Request::url('/myurl') active @endif"></span>

Sorry missed that part of the question :).

I didn't test it this way but it should work:

@if (Request::url($variable or $pattern .'/restofuri')
0
votes

A little late to the party, but i also had the same issue and solved it with the laravel helper function url()->current() and the localization package helper function localizeURL

<a href="{{LaravelLocalization::localizeURL(trans('routes.my-route'))}}"
   class="{{(url()->current() == LaravelLocalization::localizeURL(trans('routes.my-route'))) ? "active" : "" }}">
   {{trans('navigation.my-route')}}</a>