将数据从控制器传递到laravel嵌套视图

时间:2015-10-30 07:43:53

标签: php laravel laravel-4

我在Laravel中有一个页面系统 - 我将数据从控制器传递到视图。

$this->data['title'] = $row->title;
$this->data['breadcrumb'] = $row->bc;

现在我按照以下方式通过了:

return View::make('Themes.Page', $this->data);

在视图文件中,我按如下方式访问数据:

{{$breadcrumb}}

我现在要做的是在嵌套视图中传递这些数据:

$this->layout->nest('content',$page, $this->data);

(内容是视图中的{{content}},将替换为$ page内容。我想像以前一样传递$ this->数据,但现在我收到错误:

未定义变量痕迹。

  

注意:Laravel版本4.2 $ this-> layout在构造函数中设置为a   模板文件(Themes.Page)

4 个答案:

答案 0 :(得分:2)

实际上,您不需要将任何单独的数据传递到您的部分页面(breadcrumb)

控制器页面

$this->data['title'] = $row->title;
$this->data['breadcrumb'] = $row->bc;

return View::make('idea.show',array("data"=>$this->data));

主视图页面

<div>
<h1>here you can print data passed from controller  {{$data['title']}}</h1>
@include('partials.breadcrumb')
</div>

您的部分档案

<div>
<h1>here also you can print data passed from controller {{$data['title']}}</h1>
<ul>
<li>....<li>
<li>....<li>
</ul>
</div>

有关此问题的详情,请查看以下链接http://laravel-recipes.com/recipes/90/including-a-blade-template-within-another-template或观看此视频https://laracasts.com/series/laravel-5-fundamentals/episodes/13

答案 1 :(得分:0)

您应该按如下方式传递数据

return View::make('Themes.Page')->with(array(
            'data'=>$this->data));

或(因为你只传递了一个变量)

return View::make('Themes.Page')->with('data', $this->data);

并且您可以通过引用$ data

将其传递给嵌套视图

答案 2 :(得分:0)

$dataForNestedView = ['breadcrumb' => $row->bc];

return View::make('Themes.Page', $this->data)->nest('content', 'page.content', $dataForNestedView);

在Themes.Page视图中渲染嵌套视图:

<div>
   {{ $content }} <!-- There will be nested view -->
</div> 

在嵌套的page.content视图中,您可以调用:

<div>
  {{ $breadcrumb }}
</div>

* div标签只是为了更好地理解。

答案 3 :(得分:0)

好的,经过激烈的搜索,我发现我使用的Laravel版本4.2中存在一个错误。 Laravel 5的作品。 对于laravel 4.2,更好的选择是在从控制器传递数据时使用View::share('data',$objectarray)传递数据对象数组。

感谢大家的帮助

相关问题