5

假设我有这个:

//controllers/BlogController.php
$data["post"] = $post = Blog::recent_post();
$data["posts_related"] = Blog::posts_related($post->category_id,5);
return View::make('blog.home', $data);

//views/sidebars/related.blade.php
@foreach($posts_related as $r)
<p>{{ $r->name }}</p>
@endforeach

//views/blog/home.blade.php
@include('sidebars.related')

我的问题是,我该如何转移:

$data["posts_related"] = Blog::posts_related($post->category_id,5);

对于视图作曲家,因为似乎我无法将参数传递给视图作曲家,但我不能确定。

我很感激任何帮助!

4

1 回答 1

31

在 View Composer 中,您可以检索传递给 View 的数据。

View::composer('sidebars.related', function($view)
{
   //$data contains category_id
   $viewdata= $view->getData();

   //Retrive based on category_id
   $posts_related = Blog::posts_related($viewdata['category_id'],5);

   //pass related post to view
   $view->with('posts_related', $posts_related);
});

现在您可以在任何地方使用:

 View::make('sidebars.related')->with(array('category_id' => 6));
于 2013-08-20T22:13:45.650 回答