我正在使用Laravel 4。我想使用Laravel的刀锋模板引擎在视图中访问@if条件内的当前URL,但我不知道如何做到这一点。

我知道可以使用<?php echo URL::current();但是在@if blade语句中是不可能的。

有什么建议吗?


当前回答

试试这个:

@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.4 相关:

全局函数

@if (request()->is('/'))
    <p>Is homepage</p>
@endif

你可以使用这段代码来获取当前URL:

echo url()->current();

echo url()->full();

这是我从Laravel的文件中得到的。

对我来说,这是最好的方法:

class="{{url()->current() == route('dashboard') ? 'bg-gray-900 text-white' : 'text-gray-300'}}"

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或路由的四种方法。

对于命名路由,我使用:

@if(url()->current() == route('routeName')) class="current" @endif