我在 Laravel 刀片中有這個簡單的回圈
@foreach ($team->players as $player)
{{$loop->first ? "(" : ""}}
{{!$loop->first ? ", " : ""}} {{$player->name}}
{{$loop->last ? ")" : ""}}
@endforeach
但我最終在開始之后和結束大括號之前有空格。像這樣
(玩家一,玩家二)
我怎么能阻止這個?
uj5u.com熱心網友回復:
你得到的空間 bcs 只有{{ }}在 Blade 模板中由 PHP 處理的東西。其余部分完全按照型別顯示在您的 HTML 中 - 因此用于格式化代碼、縮進等的空格都顯示在您的 HTML 中。如果這些空格位于文本中間,您將看到它們在瀏覽器中呈現。
@foreach ($team->players as $player)
{{$loop->first ? "(" : ""}}
// ^-- space here, if you had text before the opening bracket you'll see it
{{!$loop->first ? ", " : ""}} {{$player->name}}
// -----------------------------^ space here, even for first name
{{$loop->last ? ")" : ""}}
// ^-- space here, shows up after last name
@endforeach
如果你想堅持使用回圈,你可以通過去掉空格,但它很亂,不太可讀:
@foreach ($team->players as $player)
{{ $loop->first ? "(" : "" }}{{! $loop->first ? ", " : ""}}{{$player->name}}{{ $loop->last ? ")" : "" }}
@endforeach
但是更好的解決方法是使用一些Laravel 的收集方法來完全避免這個問題:
({{ $team->players->implode('name', ', ') }})
uj5u.com熱心網友回復:
讓我向您展示一個更好的方法:洗掉foreach并使用implode.
@isset($team->players)
{{ '('. implode(', ', $team->players). ')' }}
@endisset
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/402140.html
上一篇:當我在laravel中將記住我的引數設定為true時,如何修復Auth::loginUsingId()的奇怪行為
下一篇:Vue鏈接的格式很奇怪
