你得到空格 bcs 只有 {{ }} 之间的东西被 PHP 在 Blade 模板中处理。其余部分会完全按照键入的内容显示在您的 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
但是,只有当您需要在显示之前实际处理或操作值时,才真正需要使用循环。如果你不这样做,there's a standard, simple solution to join up an array of values in PHP,使用implode()。在您的情况下,您首先需要从您的集合中生成names 的数组以传递给implode()。可能是这样的:
({{ implode(', ', array_column($team->players->toArray(), 'name')) }})
但这也有点笨拙和过于复杂。您正在使用 Laravel,并且您的数据是一个集合,因此调查 the Collection methods available 是有意义的。果然,there's an implode() method 让一切变得更简单:
({{ $team->players->implode('name', ', ') }})