doujiazong0322 2014-11-20 16:11
浏览 69
已采纳

Laravel:包含带控制器逻辑的视图

I come from the symfony (v1) world, where we had two types of partial rendering: partials, which loaded the same as:

@include('some.view')

and controllers, which would act the exact same way but would be ran with some controller logic behind hit. So, calling the same as above would first go to the matching some.view controller, and operate with the logic it had.

I'm trying to do the same with Laravel. Basically, I have this:

@foreach($array as $thing)
  @include('controller.like.view', array('thing' => $thing))
@endforeach

... and I'd like my included view to run something like this (this is just an example, the actual code is a lot more complicated, otherwise I'd just write it with an if clause in Blade):

...
if ($thing%2) {
      return 'a';
}

return 'b';

... so that only 'a' or 'b' would be printed in my loop. What's the best way to achieve this without having a bunch of PHP code in a Blade template?

  • 写回答

1条回答 默认 最新

  • douquan9826 2014-11-20 16:16
    关注

    Why not just like that?

    @foreach($array as $thing)
        @if($thing%2)
            a
        @else
            b
        @endif
    @endforeach
    

    In general though, it's mostly a good way to prepare the data in your controller before passing it to the view. This way the view is just for presenting the data.

    You could also write a little helper function or even a full class (with optional Facade for easy access) But it really depends on your needs

    Update

    I'm not sure this is the best solution for you but it's the only one I can think of.
    Put as much of the logic as you can in your "thing" class and then use that in the included view. Here's an example:

    class Thing {
        public function isA(){
            // do the magic
            return true;
        }
    }
    

    View

    @if($this->isA())
        a
    @else
        b
    @endif
    

    Update 2

    Or to make a bit more like the controller from symfony you described:

    class Thing {
        public function getVars(){
            // do stuff
            return array(
                    'all' => 'the',
                    'vars' => 'you',
                    'need' => 'in',
                    'the' => 'view'
                );
        }
    }
    

    And then when you include the view

    @include('item', $thing->getVars())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?