【问题标题】:Laravel 4 + pass variable to master layoutLaravel 4 +将变量传递给主布局
【发布时间】:2014-05-22 16:36:05
【问题描述】:

我正在尝试将变量传递给我的“主”布局:

//views/dashboard/layouts/master.blade.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>

<body>
  @yield('site.body');
  {{{ isset($test) ? $title:'Test no exists :) ' }}}
</body>
</html>

现在在我的 DashboardController 中:

class DashboardController extends BaseController
{
    public $layout = "dashboard.layouts.master"; 

    // this throw error : Cannot call constructor
    //public function __construct()
    //{
    //    parent::__construct();
    //    $this->layout->title = 'cry...';
    //} 

    // this throw error : Attempt to assign property of non-object 
    // and I understand it, coz $layout isn't an object

    //public function __construct()
    //{
    //    $this->layout->title = 'cry...';
    //} 

    public function action_doIndex()
    {
        $this->layout->title = 'this is short title';
        $this->layout->body = View::make('dashboard.index');

    }

    public function action_doLogin()
    {
        //$this->layout->title = 'this is short title'; // AGAIN ???
        $this->layout->body = View::make('dashboard.forms.login');
    }

    public function action_doN()
    {
       // $this->layout->title = 'this is short title'; // AND OVER AGAIN ?!?!
    }

} 

我只想设置一次 $title 变量,当我想这样做时 - 覆盖它。 现在我每次调用另一个方法时都必须设置变量:/

如何做到这一点?如何为此“主”布局仅设置一次 $title 变量??

Symphony2 有 before() / after() 方法 - laravel 有什么?

【问题讨论】:

    标签: layout laravel-4 blade


    【解决方案1】:

    您可以使用View::composer()View::share() 将变量“传递”到您的视图中:

    public function __construct()
    {
        View::share('title', 'cry...');
    }
    

    这是作曲家:

    View::composer('layouts.master', function($view)
    {
        $view->with('name', Auth::check() ? Auth::user()->firstname : '');
    });
    

    如果您的所有视图都需要它,您可以:

    View::composer('*', function($view)
    {
        $view->with('name', Auth::check() ? Auth::user()->firstname : '');
    });
    

    您甚至可以为此创建一个文件,例如 app/composers.php 并将其加载到您的 app/start/global.php

    require app_path().'/composers.php';
    

    【讨论】:

    • 不错的答案,正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    • 2016-11-20
    • 2017-01-06
    • 2011-06-19
    • 2013-04-13
    • 1970-01-01
    • 2022-11-11
    相关资源
    最近更新 更多