[英]Laravel 4.2 blade: check if empty
在 Laravel 刀片中你可以做:
{{ $variable or 'default' }}
這將檢查是否設置了變量。 我從數據庫中獲取了一些數據,那些變量總是被設置的,所以我不能使用這個方法。
我正在尋找用於執行此操作的速記“刀片”function:
{{ ($variable != '' ? $variable : '') }}
很難使用這篇文章或代碼來做這件事,因為我不知道如何用鏈接或類似的東西來做:
<a href="{{ $school->website }}" target="_blank">{{ $school->website }}</a>
我試過了:
{{ ($school->website != '' ? '<a href="{{ $school->website }}" target="_blank">{{ $school->website }}</a>' : '') }}
但是,它不起作用。 而且,我想讓我的代碼盡可能短;)
有人可以向我解釋嗎?
更新
我不使用 foreach 因為,我從數據庫中得到一個 object(一所學校)。 我通過以下方式將它從我的 controller 傳遞到我的視圖:
$school = School::find($id);
return View::make('school.show')->with('school', $school);
所以,我不想在每個 $variable(如 $school->name)周圍創建一個@if($value != ''){}
。
試試這個:
@if ($value !== '')
{{ HTML::link($value,'some text') }}
@endif
在這種情況下,我更喜歡@unless
指令以提高可讀性。
@unless ( empty($school->website) )
<a href="{{ $school->website }}" target="_blank">{{ $school->website }}</a>
@endunless
{{ ($school->website != '' ? '<a href="{{ $school->website }}" target="_blank">{{ $school->website }}</a>' : '') }}
改成
{{ ($school->website != '') ? '<a href="' . $school->website . '" target="_blank">' . $school->website . '</a>' : '' }}
或相同的代碼
{{ ($school->website != '') ? "<a href='$school->website' target='_blank'>$school->website</a>" : '' }}
使用php 7,您可以使用null合並運算符。 這是@ m0z4rt答案的簡寫。
{{ $variable ?? 'default' }}
{{ isset($variable) ? $variable : 'default' }}
我想知道為什么沒有人談論$variable->isEmpty()
它看起來比其他更好。 可以像:
@if($var->isEmpty())
Do this
@else
Do that
@endif
從Laravel 5.4開始,也可以使用@isset指令。
@isset($variable)
{{-- your code --}}
@endisset
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.