【问题标题】:Default values for Laravel 5.4+ blades new components?Laravel 5.4+ 刀片新组件的默认值?
【发布时间】:2017-03-23 03:07:34
【问题描述】:

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

是否有简写或刀片标记来为传入的变量设置默认值?

例如,在上面,如果我没有传入“type”,我会得到一个undefined variable 错误。我可以这样做:

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

但是上面的内容感觉很冗长,特别是如果变量在多个地方使用。

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.4


    【解决方案1】:

    我认为不会。

    话虽如此,刀片有 or 运算符来包装 isset() 调用 (see docs)。

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

    如果您运行的是 php 7,这是Null coalescing operator 的情况。

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

    两者都会让您的呼叫站点更受欢迎。

    【讨论】:

    • 不错,我喜欢。干杯
    【解决方案2】:

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

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

    就是这样。
    这在 laravel 8 中对我有用

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 2021-07-29
      • 1970-01-01
      • 2017-11-13
      • 2015-12-03
      • 2017-09-06
      • 2017-09-29
      • 2017-08-28
      • 2017-10-05
      相关资源
      最近更新 更多