我目前使用{{action('Namespace'Class@method')}}
生成我的应用程序url。我如何检查当前页面请求是否映射到当前操作Namespace'Class@method
?
我想这样做:
<a href="{{action('Namespace'Class@method')}}
@if (currentAction('Namespace'Class@method'))
class="active"
@endif
>Some link</a>
我如何在Laravel 5中实现这一点?
没有内置的方法,但是您可以使用Route::currentRouteAction()
检索当前操作名称。不幸的是,此方法将返回一个完全命名空间的类名。所以你会得到这样的内容:
App'Http'Controllers'FooBarController@method
你可以检查这个或者使用像ends_with
这样的东西,所以你不必指定完整的路径:
@if(ends_with(Route::currentRouteAction(), 'FooBarController@method'))
你也可以考虑用'as' => 'route.name'
来命名。这将允许您使用:Route::is('route.name')
实际上我将其简化为以下代码:
<li class="@if(Route::is('getLogin')) active @endif"><a href="{{URL::route('getLogin')}}">Login</a></li>
假设你已经命名了路由。这首先是一个好主意,因为你可能会改变一个动作的url,而不需要通过整个项目来改变到那个动作的链接。
我知道这是旧的,但不管怎样,它是值得的。
Laravel有两个内置的帮助方法来引用url的action和route。
action
你的路由文件应该是这样的:
Route::get('/funtastic', 'FuntasticController@show');
你的叶片视图应该是这样的
<a href="{{action('FuntasticController@show')}}
@if(action('FuntasticController@show') == Request::url())
class="active"
@endif
>Some link</a>
route
如果你使用命名路由。
<a href="{{route('namedRoute')}}
@if(route('namedRoute') == Request::url())
class="active"
@endif
>Some link</a>
我是这样做的,没有任何命名路由
<a class="{{ str_contains(request()->url(), '/some-page') ? 'active' : '' }}" href="/some-page">Some Page</a>
这不是一个完美的解决方案,但它适用于大多数情况
对我来说效果很好。
<a class="@if ('Route::current()->getName() == 'device_media') active @endif" href="{{ route('device_media', ['brand_slug'=>$brand->slug, 'slug'=>$device->slug]) }}" > Media</a>