Laravel 5.4+ 刀片新组件的默认值?

Default values for Laravel 5.4+ blades new components?

Laravel 5.4+ 允许以下结构的组件:

<div class="alert alert-{{ $type }}">
    <div class="alert-title">{{ $title }}</div>
    {{ $slot }}
</div>

被称为:

@component('alert', ['type' => 'danger'])
    @slot('title') 
        oh no 
    @endslot
    Foo
@endcomponent

是否有 shorthand 或 blade 标记来为传入的变量设置默认值?

例如,在上面,如果我不传入 "type",我会收到 undefined variable 错误。我可以这样做:

<div class="alert alert-{{ isset($type) ? $type : 'default' }}">

但是上面的感觉很冗长,尤其是当变量在多个地方使用时。

我不这么认为。

说过 blade 有 or 运算符来包装 isset() 调用 (see docs)。

<div class="alert alert-{{ $type or 'default' }}">

如果您是 运行 php 7,则 Null coalescing operator.

就是这种情况
<div class="alert alert-{{ $type ?? 'default' }}">

两者都会使您的呼叫站点更加整洁。

在与您的组件相关的 php 文件中,为您的参数设置一个默认值:

public function __construct($type = 'text')
{
    $this->type = $type;
}

就是这样。
这在 laravel 8

对我有用