【问题标题】:How to use collections function in blade template?如何在刀片模板中使用集合功能?
【发布时间】:2016-08-15 00:05:23
【问题描述】:

我尝试在 Blade 模板中控制输出流,为此我在模板中使用集合功能:

@if(count($item->images))
   @if($item->images->count() > 1 && $item->images->count() < 3)
        {{$chunk = $item->images->forPage(0, 1)}} // It displays $chunk like as object (string) in template
   @endif
@endif

在此之后,我尝试在$chunk 中显示收藏:

@foreach($chunk as $image)
   // Show here
@endforeach

【问题讨论】:

  • 我无法理解您想要实现的目标。能否请您详细说明
  • 我尝试在模板中使用forPage函数:{$chunk = $item-&gt;images-&gt;forPage(0, 1)
  • 在我尝试在下面的同一模板中迭代结果 $chunk 之后
  • 您在{{ }} 之间放置的任何内容都会与它们之间的代码输出一起打印出来。
  • 检查我的答案,你是这个意思吗?

标签: laravel laravel-5.2


【解决方案1】:

你不能这样做吗,

@if(count($item->images))
   @if($item->images->count() > 1 && $item->images->count() < 3)
        @foreach($item->images->forPage(0, 1) as $image)
           // Show here
        @endforeach
   @endif
@endif

【讨论】:

  • 是的,它有效,但我尝试在模板末尾使用一个循环来更优雅地做到这一点。
  • 这和我想的差不多
  • 虽然你也可以使用php标签,但这不是标准
【解决方案2】:
{{ some code php }}

是一样的

<?php echo some php code; ?>

不一样

<?php some php code; ?>

您可以做的就是将信息传递给循环:

@if(count($item->images))
   @if($item->images->count() > 1 && $item->images->count() < 3)
        @foreach($item->images->forPage(0, 1) as $image)
            // do stuff
        @endforeach
   @endif
@endif

或者您可以使用诸如radic/blade-extensions (http://robin.radic.nl/blade-extensions/) 之类的包并使用@set() 来设置变量。

或者你可以在模板中使用普通的 PHP,但这当然不是很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 2021-11-21
    • 2019-10-11
    • 2017-10-17
    • 2018-09-25
    • 1970-01-01
    • 2016-06-11
    相关资源
    最近更新 更多