[英]Laravel get current route
I have some navigation links and I want to get the current route in laravel 5 so that I can use the class
active
in my navigations. 我有一些导航链接,我想在laravel 5中获取当前路线,以便我可以在我的导航中使用
active
的class
。 Here are the sample links: 以下是示例链接:
<li class="active"> <a href="/">Home</a> </li>
<li> <a href="/contact">Contact</a> </li>
<li> <a href="/about">About</a> </li>
As you can see, in the Home
link there is the active class
which means that it is the current selected route. 如您所见,在
Home
链接中有active class
,这意味着它是当前选定的路由。 But since I am using laravel blade
so that I would not repeat every navigation links in my blades, I can't use the active class because I only have the navigation links in my template.blade.php
. 但由于我使用
laravel blade
所以我不会重复我的刀片中的每个导航链接,我不能使用活动类,因为我只有我的template.blade.php
的导航链接。 How can I possibly get the current route and check if it is equal to the current link? 我怎样才能获得当前路由并检查它是否等于当前链路? Thank you in advance.
先感谢您。
$uri = Request::path()
查看文档
You can use named routes like 您可以使用命名路由
Route::get('/', ['as'=>'home', 'uses'=>'PagesController@index']);
and then in the view you can do the following 然后在视图中,您可以执行以下操作
<li {!! (Route::is('home') ? 'class="active"' : '') !!}>
{!! link_to_route('home', 'Home') !!}
</li>
So I got it working with some little tricks. 所以我得到了一些小技巧。 For example the url in the address bar is
http://localhost:8000/tourism/places
. 例如,地址栏中的URL是
http://localhost:8000/tourism/places
。
If I will use the Request::path()
method, I will get tourism/places
. 如果我将使用
Request::path()
方法,我将获得tourism/places
。 But what I wanted to get is the tourism
part only so what I did is this: 但我想得到的只是
tourism
部分所以我所做的就是:
$currentPath = Request::path();
$values = explode("/", $currentPath);
$final = $values[0];
Now the $final
variable will have the value "tourism"
. 现在
$final
变量将具有值"tourism"
。
Now to make the variable load globally, I included the code in the AppServiceProvider.php
inside the public function boot()
. 现在为了全局变量加载,我将代码包含在
public function boot()
内的AppServiceProvider.php
。
public function boot()
{
$currentPath = Request::path();
$values = explode("/", $currentPath);
$final = $values[0];
view()->share('final', $final);
}
And lastly in my blade template, 最后在我的刀片模板中,
<li @if ($final== "tourism") class="active" @endif>
<a href="/tourism/places">Places</a>
</li>
Simple way is always better, just use the same function you use to generate links and it will give you all, including the flexibility to use wild cards
简单的方法总是更好,只需使用您用来生成链接的相同功能,它将为您提供所有功能,包括
flexibility to use wild cards
的flexibility to use wild cards
<a class="nav-link {{ Request::url() === route("products.list", [$group_key]) ? 'active' : '' }}"
href="{{ route("products.list", [$group_key]) }}"
>
LInk text
</a>
Plus, you still are going to have only one place to manage URL-s - your router files. 此外,您仍然只有一个地方可以管理URL-s - 您的路由器文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.