对不起,我不知道怎么说这个问题。我是Laravel的新手,我想要显示照片,或者如果没有照片我想要显示占位符。这有效,但必须有一个比这更好的方法。
@foreach ($items as $item)
<?php $totalpics=0; ?>
<div class="col-md-4">
<div class="card mb-4 box-shadow">
@if(! empty($item->photos) )
@foreach ( $item->photos as $photo )
@if ($photo->photo)
<a href="/storage/images/large/{{ $photo->photo }}"><img src="/storage/images/small/{{ $photo->photo }}" class="card-img-top" alt="{{ $item->name }}"></a>
<?php $totalpics++; ?>
@endif
@endforeach
@if(1 > $totalpics)
<a href="/items/{{ $item->id }}"><img class="card-img-top" data-src="holder.js/100px225?theme=thumb&bg=55595c&fg=eceeef&text=Thumbnail" alt="{{ $item->name }}"></a>
@endif
答案 0 :(得分:1)
当for循环中没有任何内容显示时,你想要实现一个for循环和一个可选语句。
Laravel使用forelse
循环(参见all blade loops in the documentation)。
基本forelse
可以是:
@forelse($items as $item)
{{$item}}
@empty
There are no items to display
@endforelse
上面的代码是伪代码,实际上不会运行
哪个会呈现为items
或文本There are no items to display
。
在您的情况下,您可以使用:
@forelse($items as $item)
<div class="col-md-4">
<div class="card mb-4 box-shadow">
@forelse ( $item->photos as $photo )
@if ($photo->photo)
<a href="/storage/images/large/{{ $photo->photo }}">
<img src="/storage/images/small/{{ $photo->photo }}" class="card-img-top" alt="{{ $item->name }}">
</a>
@endif
@empty
<a href="/items/{{ $item->id }}">
<img class="card-img-top" data-src="holder.js/100px225?theme=thumb&bg=55595c&fg=eceeef&text=Thumbnail" alt="{{ $item->name }}">
</a>
@endforelse
</div>
</div>
@endforeach
旁注,如果您的photo
附加item
模型,但photo
模型没有设置photo
属性,则不会呈现任何照片,即将使用for
循环,但if
语句将失败。
答案 1 :(得分:0)
你可以做到
@foreach ($items as $item)
<div class="col-md-4">
<div class="card mb-4 box-shadow">
@unless($item->photos)
<a href="/items/{{ $item->id }}"><img class="card-img-top" data-src="holder.js/100px225?theme=thumb&bg=55595c&fg=eceeef&text=Thumbnail" alt="{{ $item->name }}"></a>
@else
@foreach ( $item->photos as $photo )
@if ($photo->photo)
<a href="/storage/images/large/{{ $photo->photo }}"><img src="/storage/images/small/{{ $photo->photo }}" class="card-img-top" alt="{{ $item->name }}"></a>
@endif
@endforeach
@endunless
答案 2 :(得分:0)
使用
在laravel 5.3+中还有另一种方法可以做到这一点 @forelse($item->photos as $photo)
<a href="/storage/images/large/{{ $photo->photo }}"><img src="/storage/images/small/{{ $photo->photo }}" class="card-img-top" alt="{{ $item->name }}"></a>
@empty
<a href="/items/{{ $item->id }}"><img class="card-img-top" data-src="holder.js/100px225?theme=thumb&bg=55595c&fg=eceeef&text=Thumbnail" alt="{{ $item->name }}"></a>
@endforelse