我正在使用Laravel 4。我想在使用Laravel的Blade模板引擎时,在视图中的@if语句内访问当前URL,但我不知道如何做。
我知道可以使用类似于
有什么建议吗?
我知道可以使用类似于
<?php echo URL::current(); ?>
的方法来实现,但在@if Blade语句内部不可能这样做。有什么建议吗?
<?php echo URL::current(); ?>
的方法来实现,但在@if Blade语句内部不可能这样做。@if (Request::is('companies'))
Companies name
@endif
与其使用 URL::path() 来检查当前路径位置,您可能希望考虑使用 Route::currentRouteName()。这样,如果您更新了路径,您就不需要再浏览所有页面以更新路径名称。
简单来说,您需要检查URL是否与X完全相同,然后显示某些内容。在控制器中:
if (request()->is('companies')) {
// show companies menu or something
}
@if (request()->is('companies'))
Companies menu
@endif
一个稍微复杂的示例 - 方法Request::is()允许使用pattern参数,例如:
if (request()->is('companies/*')) {
// will match URL /companies/999 or /companies/create
}
正如您可能知道的那样,每个路由都可以分配一个名称,在routes/web.php
文件中,它看起来像这样:
Route::get('/companies', function () {
return view('companies');
})->name('comp');
那么如何检查当前路由是否为“comp”呢?相对容易:
if (\Route::current()->getName() == 'comp') {
// We are on a correct route!
}
如果您正在使用路由名称,您可以检查请求是否匹配路由名称。
if (request()->routeIs('companies.*')) {
// will match routes which name starts with companies.
}
或者
request()->route()->named('profile')
将匹配名为 "profile" 的路由。 因此,这是检查当前URL或路由的四种方式。
Request::is('companies')
是 Laravel 4 中的实现方式。 - Joundill使用 Laravel 的 path 可以另一种方式来编写 if 和 else 语句。
<p class="@if(Request::is('path/anotherPath/*')) className @else anotherClassName @endif" >
</p>
试试这个:
@if(collect(explode('/',\Illuminate\Http\Request::capture()->url()))->last() === 'yourURL')
<li class="pull-right"><a class="intermitente"><i class="glyphicon glyphicon-alert"></i></a></li>
@endif
适用于 Laravel 5.5 +
<a class="{{ Request::segment(1) == 'activities' ? 'is-active' : ''}}" href="#">
<span class="icon">
<i class="fas fa-list-ol"></i>
</span>
Activities
</a>
有许多方法可以实现,其中我经常使用的一种
Request::url()
Try This:
<li class="{{ Request::is('Dashboard') ? 'active' : '' }}">
<a href="{{ url('/Dashboard') }}">
<i class="fa fa-dashboard"></i> <span>Dashboard</span>
</a>
</li>
@if(request()->path()=='/path/another_path/*')
@endif
<a href="{{ URL::to('/registration') }}">registration </a>