laravel刀片模板中的Override部分抛出未定义的变量错误 [英] Override section in a laravel blade template throwing undefined variable errors

查看:96
本文介绍了laravel刀片模板中的Override部分抛出未定义的变量错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 4和刀片模板,并且在尝试扩展模板时遇到问题.

I am using Laravel 4 and blade templates, and running into an issue when I try and extend a template.

在我的布局中,

@yield('content')

在我的页面中,我有

@section('content')
    Welcome {{ $name }}
@stop

效果很好,我创建了另一个页面,该页面与我的第一个页面非常相似,只想更改覆盖管理内容部分.模板中的其他部分都很好.

which works fine, I've created another page very similar to my first, and just want to change override the admin content section. The other sections in the template are fine.

所以我扩展页面,然后做

so I extend my page, and do

@section('content')
    Hello!
@stop

我收到带有$ name变量的未定义通知.

I get an undefined notice with the $name variable.

我尝试过

@section('content')
    Hello!
@overwrite

以同样的方式,我得到通知错误. 我检查了控制器,它使用的是正确的模板.我不是在打电话给@parent,所以我不明白,我该如何覆盖模板中没有通知错误的部分?

and same deal, I get the notice error. I checked my controller and it IS using the correct template. I am not calling @parent so I don't understand, how can I overwrite a section in a template with out notice errors?

推荐答案

刀片布局在渲染任何子级之前会沿树一直向上到达路线或主视图.因此,扩展其他视图的嵌套视图必须始终先呈现其父视图.结果,包含节的父视图将始终在子视图之前呈现.

Blade layouts work their way up the tree to the route or master view before rendering any of the children. Thus, nested views that extend others must always have their parent rendered before they are. As a result, parent views that contain sections will always be rendered prior to the child.

要解决您遇到的问题,最好只嵌套不覆盖包含变量的父部分的页面,因为父内容始终会在子之前呈现.

To overcome the problem you are experiencing it is a good idea to only ever nest pages that don't overwrite parents sections that contain variables, as the parents content will always be rendered before the child.

由于不能始终遵循上述理想,或者仍然需要父节内容,因此一种很好的替代方法是使用视图编写器.视图编辑器使您有机会在渲染任何特定视图时声明变量.

As the above ideal can't always be adhered to or a parents section content is still required, a good alternative method would be to use view composers. View composers give you an opportunity to declare variables for any specific view whenever they are rendered.

View::composer(array('pages.admin'), function($view)
{
    $view->with('name', Auth::user()->username);
});

另一种替代方法是使用视图创建器.实例化而不是渲染视图后立即解雇创作者.此方法允许您在呈现视图之前根据需要覆盖变量.

Another alternative would be to use a view creator. Creators are fired the moment a view is instantiated rather than rendered. This method allows you to overwrite the variable should you so wish prior to the view being rendered.

View::creator(array('pages.admin'), function($view)
{
    $view->with('name', Auth::user()->username);
});

您可以在文档此处中详细了解这些方法. (或者对于Laravel 5文档,此处.)

You can read up more about these methods in the documentation here. (Or here for the Laravel 5 documentation.)

这篇关于laravel刀片模板中的Override部分抛出未定义的变量错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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