如何使用 Laravel 的 Blade 模板将变量传递给布局? [英] How do I pass a variable to the layout using Laravel' Blade templating?

查看:23
本文介绍了如何使用 Laravel 的 Blade 模板将变量传递给布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Laravel 4 中,我的控制器使用 Blade 布局:

class PagesController extends BaseController {受保护的 $layout = 'layouts.master';}

主布局已输出变量标题,然后显示一个视图:

<代码>...<title>{{ $title }}</title>...@yield('内容')……

但是,在我的控制器中,我似乎只能将变量传递给子视图,而不是布局.例如,一个动作可以是:

公共函数 index(){$this->layout->content = View::make('pages/index', array('title' => '主页'));}

这只会将 $title 变量传递给视图的内容部分.如何将该变量提供给整个视图,或者至少提供给主布局?

解决方案

如果你在你的内容布局中使用 @extends 你可以使用这个:

@extends('master', ['title' => $title])

注意与上面相同的方法适用于孩子,例如:

<块引用>

@include('views.subView', ['my_variable' => 'my-value'])

用法

然后将变量传递到哪里,像这样使用它:

<title>{{ $title ??'默认标题' }}</title>

In Laravel 4, my controller uses a Blade layout:

class PagesController extends BaseController {
    protected $layout = 'layouts.master';
}

The master layout has outputs the variable title and then displays a view:

...
<title>{{ $title }}</title>
...
@yield('content')
....

However, in my controller I only appear to be able to pass variables to the subview, not the layout. For example, an action could be:

public function index()
{
    $this->layout->content = View::make('pages/index', array('title' => 'Home page'));
}

This will only pass the $title variable to the content section of the view. How can I provide that variable to the whole view, or at the very least the master layout?

解决方案

If you're using @extends in your content layout you can use this:

@extends('master', ['title' => $title])

Note that same as above works with childs, like:

@include('views.subView', ['my_variable' => 'my-value'])

Usage

Then where variable is passed to, use it like:

<title>{{ $title ?? 'Default Title' }}</title>

这篇关于如何使用 Laravel 的 Blade 模板将变量传递给布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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