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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?