laravel 限制 Blade foreach 循环中的结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33393376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limiting the results in Blade foreach loop
提问by Stefan Neuenschwander
Alright so I'm pretty new to Blade, and I did manage to get all the results that I asked for on my page. Now I want to show only 10 of the total items on my page and I seem to struggle with it, tried the array_slice without any success so far. Any suggestions?
好的,所以我对 Blade 还很陌生,我确实设法在我的页面上获得了我要求的所有结果。现在我只想在我的页面上显示全部项目中的 10 个,但我似乎对此很挣扎,尝试了 array_slice 到目前为止没有任何成功。有什么建议?
Below the code I'm currently using
在我目前使用的代码下方
{{--@foreach ($element['subs']->slice(0, 10) as $item)--}}
@foreach ($element['subs'] as $item)
<div class="highlight {{ $element['class'] }}">
<div class="el-inner-news">
<div class="image-news">
<a href="{{ $item['news-item']['slug'] }}"> <img src="{{ $item['news-item']['image'] or "/assets/frontend/baywest/images/newsholder.png" }}" class="center-img" alt="{{ $item['news-item']['title'] }}" /> </a>
</div>
<div class="desc-news">
<div class="title-highlight">
<a href="{{ $item['news-item']['slug'] }}">{{ $item['news-item']['title'] }}</a>
</div>
<div class="text-highlight">
{!! $item['news-item']['textfield'] !!}
</div>
<div class="learn-more-news">
<a href="{{ $item['news-item']['slug'] }}">{{ $item['news-item']['read-more'] or "Learn more" }} </a>
</div>
</div>
</div>
</div>
@endforeach
Thanks in advance!
提前致谢!
回答by Mrquestion
A cleaner way to do it could be this if it is a collection:
如果它是一个集合,那么更简洁的方法可能是这样:
@foreach ($element['subs']->slice(0, 10) as $item)
...Code
@endforeach
another way for collections:
另一种收集方式:
@foreach ($element['subs']->take(10) as $item)
...Code
@endforeach
or this if it is an array:
或者如果它是一个数组:
@foreach (array_slice($element['subs'], 0, 10) as $item)
...Code
@endforeach
回答by Pawel Bieszczad
You should limit the results in controller, but here's how you can accomplish this in a blade. Not pretty.
您应该限制控制器中的结果,但这里是您如何在刀片中完成此操作的方法。不漂亮。
<?php $count = 0; ?>
@foreach ($element['subs'] as $item)
<?php if($count == 10) break; ?>
// Your code
<?php $count++; ?>
@endforeach
回答by wasthishelpful
Late, but to extend Pawel Bieszczad's answerin laravel 5.4 you can use the index
property of the loop variable:
晚了,但要在 laravel 5.4 中扩展Pawel Bieszczad 的答案,您可以使用循环变量的index
属性:
@foreach ($element['subs'] as $item)
@if($loop->index < 10)
// Your code
@endif
@endforeach
回答by Adrian Hernandez-Lopez
Since Laravel 5.3there is a blade way to do this by using the Loop variable and the break directive:
从Laravel 5.3 开始,有一种刀片方式可以通过使用 Loop 变量和 break 指令来做到这一点:
@foreach ($element['subs'] as $item)
@if($loop->iteration > 10)
@break
@endif
{{-- Your loop code here --}}
@endforeach