Laravel 5获取视图名称 [英] Laravel 5 get view name

查看:249
本文介绍了Laravel 5获取视图名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力获取L5中的视图名称.就像在WP中一样,我想为样式添加特定的页面名称(视图名称),如下所示:

I'm struggling to get the view name in L5. Just as in WP, I'd like to add a specific page name (view name) for styling, like so:

<!-- View name: login.blade.php !-->
<div id="page" class="page-login">
    <h1>Inloggen</h1>
</div>

<!-- View name: register.blade.php !-->
<div id="page" class="page-register">
    <h1>Registreren</h1>
</div>

在L4中,可以使用composer在所有视图之间共享var(

In L4 it can be done using composer to share the var across all views (How can I get the current view name inside a master layour in Laravel 4?). But I only need the view name once for my master layout.

这样做:

<div id="page" class="page-{{ view()->getName() }}">

出现以下错误Call to undefined method Illuminate\View\Factory::getName().

提前谢谢!

推荐答案

通过在启动方法中添加视图编写器并使用'*'与所有视图共享它来更新您的AppServiceProvider:

Update your AppServiceProvider by adding a view composer to the boot method and using '*' to share it with all views:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;    

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function($view){
            $view_name = str_replace('.', '-', $view->getName());
            view()->share('view_name', $view_name);
        });

    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

{{$view_name}}将可用于您的刀片服务器模板.

{{$view_name}} will be made available to your blade templates.

这篇关于Laravel 5获取视图名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆