drdawt9210 2014-01-07 18:26
浏览 48
已采纳

Laravel4 - 尝试创建像部分一样的小部件,它将传递/接受参数以获取正确的数据

Within my views I am trying to reuse a partials, so I can create a list of latest posts anywhere in the site / sidebar by using the blade @include where the passed variable is the number of posts to be included, like this:

@include('widgets.lastestposts', array('numPosts' => '10')

However the problem I have is how to get the Post data for the correct number of posts within the partial?

I could pass through a list of all posts via Post::all() using the controller or even a View::composer and then within the partial use a @for|@endfor loop to only show the correct number based on the 'numPosts' value.

However this doesn't feel right and I am sure there must be a better way than pulling a complete list of Posts when I may only need 5 or 10.

I tried View::composers but I could find how to pass through a variable so I can get the correct number of Posts returned. I can't access the parameter 'numPosts' via

$view->getdata() 

as I expect 'numPosts' needs to be passed to the view via the controller, rather than the Blade file - either that or I messed up!

Am I missing something easy here or is what I am looking to do actually a very bad idea and I should be doing something else?

Any pointers are most gratefully received. Thanks!

(ps - I was looking to be able to do this via the blade file rather than setting up the number of posts in the controller to allow our designers/HTML coders to simply add the widgets and parameters to the views rather than have to mess with controllers.)

  • 写回答

2条回答 默认 最新

  • duanchijie2323 2014-01-07 19:24
    关注

    I would do this using View Composers. You can pass data to the composer with your include:

    @include('widgets.lastestposts', array('numPosts' => '10')
    

    and then from within the view composer you should be able to access that param like so:

    View::composer('widgets.latestposts', function($view)
    {
       $view_data= $view->getData();
       $post_count = $view_data['numPosts'];
    
       //You will have to implement something to do this
       $post_data = Post::getLatestPosts($post_count); 
    

    and then you can pass the post data back with:

       $view->with('posts', $post_data);
    }
    

    and then from within your blade partial widgets.latestposts you can iterate over $posts to display the posts.

    I know you said in your post that you tried this method, but I am fairly certain that this approach should work. Double check all your filenames, file extensions (.blade.php) etc...

    Hope this works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!