【问题标题】:Conditional Blade component slots条件刀片组件插槽
【发布时间】:2021-10-16 02:42:49
【问题描述】:

我有一个名为 Person 的 Blade 组件,它有不同的插槽我想填充。

<div class="person">
  <img src="{{ $image_url }}" alt="{{ $image_alt }}">
  {{ $name }}
  {{ $information }}
  <a class="button button-primary" href="{{ $link }}" target="_blank">Homepage</a>
</div>

我有各种模板文件,我正在做一个 foreach 并且我想使用 people 组件来显示信息。

@if ($persons)
  @foreach ($persons as $person)
    @component('components.person')
      @slot('image_url')
        {{ $person['person_image'] }}
      @endslot

      @slot('name')
        {{ $person['person_name'] }}
      @endslot

      @slot('information')
        {!! $person['person_information'] !!}
      @endslot

      @slot('link')
        {{ $person['person_link'] }}
      @endslot
    @endcomponent
  @endforeach
@endif

有时某些字段可能为空。例如,有时有人没有图片或主页,在这种情况下,我不想在主页上显示该空白字段。

逻辑说我应该将issset() 或empty() 添加到我的组件文件中,如下所示:

<div class="person">
  @empty ($image_url)
    <img src="{{ $image_url }}" alt="{{ $image_alt }}">
  @endempty
  
  @isset ($name)
    {{ $name }}
  @endisset
  
  @isset ($information)
    {{ $information }}
  @endisset
  
  @isset ($link)
    <a class="button button-primary" href="{{ $link }}" target="_blank">Homepage</a>
  @endisset  
</div>

但这似乎根本不起作用。它要么删除所有内容,要么什么都不删除(取决于是否使用 @isset() 或 @empty() )。

所以我的问题是:是否可以在 foreach 循环中有条件地填充组件槽?

【问题讨论】:

    标签: php blade laravel-blade


    【解决方案1】:

    这是不久前的,但您可以使用空合并运算符来定义默认值

    <div class="person">
      <img src="{{ $image_url }}" alt="{{ $image_alt }}">
      {{ $name ?? '' }}
      {{ $information ?? '' }}
      <a class="button button-primary" href="{{ $link }}" target="_blank">Homepage</a>
    </div>
    

    【讨论】:

      【解决方案2】:

      使用@if和空强制运算符并设置默认值:

      <div class="person">
        @if ($image_url ?? null)
          <img src="{{ $image_url }}" alt="{{ $image_alt ?? '' }}">
        @endif
        
        <span>{{ $name ?? 'No name' }}</span>
        
        {{ $information ?? null }}
      
        
        @if ($link ?? null)
          <a class="button button-primary" href="{{ $link }}" target="_blank">Homepage</a>
        @endif 
      </div>
      

      【讨论】:

        【解决方案3】:

        最好按照你说的在上层检查它们,但请注意,如果它们有名称槽,你应该将一些东西传递到槽中,所以你应该调用:

        @slot('myslot')
          @if($myobject->value)
            <h5>
               Show
            </h5>
          @endif
        @endslot
        

        【讨论】:

          【解决方案4】:

          这对我有用。

          @isset($qualitycheck)
             <a class="dropdown-item p-2" href="{{ $qualitycheck }}">Quantity Check</a>
          @endisset
          

          【讨论】:

            猜你喜欢
            • 2015-09-19
            • 2017-12-20
            • 2020-07-01
            • 2021-02-06
            • 2017-08-30
            • 2015-03-10
            • 2018-07-28
            • 1970-01-01
            • 2022-09-22
            相关资源
            最近更新 更多