我正在使用Laravel 4。我想使用Laravel的刀锋模板引擎在视图中访问@if条件内的当前URL,但我不知道如何做到这一点。
我知道可以使用<?php echo URL::current();但是在@if blade语句中是不可能的。
有什么建议吗?
我正在使用Laravel 4。我想使用Laravel的刀锋模板引擎在视图中访问@if条件内的当前URL,但我不知道如何做到这一点。
我知道可以使用<?php echo URL::current();但是在@if blade语句中是不可能的。
有什么建议吗?
当前回答
对于命名路由,我使用:
@if(url()->current() == route('routeName')) class="current" @endif
其他回答
我会这样做:
@if (Request::path() == '/view')
// code
@endif
其中'/view'是routes.php中的视图名。
你可以使用:Request::url()来获取当前的url,这里有一个例子:
@if(Request::url() === 'your url here')
// code
@endif
Laravel提供了一种方法来确定URL是否与模式匹配
if (Request::is('admin/*'))
{
// code
}
请查看相关文档获取不同的请求信息:http://laravel.com/docs/requests#request-information
你也可以使用Route::current()->getName()来检查你的路由名。
例如:routes.php
Route::get('test', ['as'=>'testing', function() {
return View::make('test');
}]);
观点:
@if(Route::current()->getName() == 'testing')
Hello This is testing
@endif
1. 检查URL是否= X
简单地说,你需要检查URL是否完全像X,然后你显示一些东西。控制器:
if (request()->is('companies')) {
// show companies menu or something
}
在Blade文件中——几乎一模一样:
@if (request()->is('companies'))
Companies menu
@endif
2. 检查URL是否包含X
一个稍微复杂一点的例子——Request::is()方法允许一个模式参数,像这样:
if (request()->is('companies/*')) {
// will match URL /companies/999 or /companies/create
}
3.检查路由的名称
你可能知道,每条路由都可以被分配一个名字,在routes/web.php文件中,它看起来是这样的:
Route::get('/companies', function () {
return view('companies');
})->name('comp');
那么如何检查当前路由是否是“comp”呢?相对容易的:
if (\Route::current()->getName() == 'comp') {
// We are on a correct route!
}
4. 按路由名称检查
如果按名称使用路由,则可以检查请求是否与路由名称匹配。
if (request()->routeIs('companies.*')) {
// will match routes which name starts with companies.
}
Or
request()->route()->named('profile')
将匹配命名为profile的路由。这是检查当前URL或路由的四种方法。
源
在Laravel中,另一种编写if和else的方法是使用path
<p class="@if(Request::is('path/anotherPath/*')) className @else anotherClassName @endif" >
</p>
希望能有所帮助