如何检索 Laravel 5 中的视图名称?

How to retrieve the view name in Laravel 5?

我尝试了多种方式,包括这里流行的 post:

但它提取的是主模板,而不是子模板名称。我使用@yield 和@extends 等。所以目前这就是我的文件系统的一部分在我看来的样子:

-Views
--Layouts
---=master.blade.php
--Shipments
---=index.blade.php

所以我的 shipments.index 文件将 @extends('layouts.master'),这样我就没有那么多冗余了。但是,参考上面的 post,我得到以下结果:

<div id="page" class="layouts.master">

这不是我想要的,我至少更喜欢"shipments.index",我不介意它更长,我只是想要它被识别。

您可以使用 Laravel View Composers

View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.

在文件app/Providers/AppServiceProvider.php中,编辑public function boot()方法

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot(Application $app)
{
    view()->composer('*', function($view) {
        view()->share('view_name', $view->getName());
    });
}

之后,在任何 blade 模板中,您现在都可以访问变量

{{ $view_name }}