繁体   English   中英

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

[英]Passing data from controller to laravel nested view

我在 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->data 但现在我收到一个错误:

未定义变量面包屑。

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

实际上您不需要将任何单独的数据传递给您的部分页面(面包屑)

控制器页面

$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/include-a-blade-template-within-another-template或观看此视频https://laracasts.com/series /laravel-5-fundamentals/episodes/13

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

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

或(因为您只传递 1 个变量)

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

此外,您可以通过引用 $data 将其传递给嵌套视图

$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 标签只是为了更好地理解。

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

谢谢大家的帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM