数据传递给视图,无法在布局中访问-Laravel控制器 [英] Data passed to view, not accessible in layout - Laravel Controllers

查看:76
本文介绍了数据传递给视图,无法在布局中访问-Laravel控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的控制器中有此

$this->layout->nest('content', 'home.index', $array);

我只能访问home.index.blade.php模板文件中$array中的数据,而不能访问我正在使用的layouts.main中的数据.

I can only access the data in $array inside the home.index.blade.php template file, and NOT in the layouts.main that I am using.

布局和视图加载正确,我只是无法访问从布局文件在控制器中传递的任何数据.

The layout & the view load correctly, I just cannot access any data passed in a controller from the layout file.

有人在那里可以提供帮助吗?

Anyone out there that can help?

要澄清-假设我想将title变量传递给我的layout.main,我将如何处理?我上面发布的方法仅允许我从index.blade.php的内容"内访问$array

To Clarify - Say I wanted to pass a title variable to my layout.main, how would I go about it? the method I posted above only allows me to access $array from within the 'content' of index.blade.php

推荐答案

要将数据传递到布局,请使用第一个参数作为变量的名称.

To pass data to the layout you use the first parameter as the name of the variable.

执行此操作时会发生什么:

What is happening when you are doing this:

$this->layout->nest('content', 'home.index', $array);

正在嵌套带有$ array参数的视图home.index.您尚未创建可在布局中使用的变量.

Is nesting the view home.index that takes a parameter of $array. You are not creating a variable that can be used in the layout.

您为布局创建的变量是$ content,它将显示传递给它的视图的内容,这特定于'nest'方法.

The variable you are creating for the layout is $content that will display the contents of the view passed to it, this is specific to the 'nest' method.

如果查看API,您会注意到控制器中声明的布局"是以下实例:Laravel\View

If you look into the API you will notice that 'layout' as declared in the controller is an instance of: Laravel\View

这有一个称为with的方法,可以为视图提供变量.

This has a method called with that supplies variables to the view.

要使用它,请尝试以下操作:

To use it try something like this:

$this->layout->with( 'myVariable' , $variable_to_pass_to_layout )
             ->nest('content', 'home.index', $array)

这篇关于数据传递给视图,无法在布局中访问-Laravel控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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