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

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

有什么建议吗?


当前回答

对于拉拉维尔 5.5+

<a class="{{ Request::segment(1) == 'activities'  ? 'is-active' : ''}}" href="#">
                              <span class="icon">
                                <i class="fas fa-list-ol"></i>
                              </span>
                            Activities
                        </a>

其他回答

与使用URL::path()来检查当前路径位置不同,您可能需要考虑Route::currentRouteName(),以便万一您更新了路径,您不需要再次浏览所有页面来更新路径名称。

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

最简单的方法是

<li class="{{ Request::is('contacts/*') ? 'active' : '' }}">Dashboard</li>

这个云捕获联系人/,联系人/创建,联系人/编辑…

@if(request()->path()=='/path/another_path/*')
@endif

您将通过使用下面的代码获得url。

例如,你的URL像https//www.example.com/testurl?test

echo url()->current();
Result : https//www.example.com/testurl

echo url()->full();
Result: https//www.example.com/testurl?test