我正在尝试在我的组件(如https://laravel.com/docs/9.x/blade#default-merged-attributes )中使用laravel属性。在本例中,:message变量不包含在$attribute列表中,而是包含在启动wiht的代码属性中(我不希望它们)。这是代码和输出。
text-with-heading.blade.php
<div {{ $attributes->merge(['class' => "m-4"]) }}>
<a href="#{{$attributes->get('id')}}">
<h4 class="text-turquoise-500 font-semibold">
{{ $title }}
</h4>
</a>
{{ $slot }}
</div>刀片文件调用组件
<x-text-with-heading :title="'Aircrafts'" id="aircrafts" :test="$test">
<div class="flex">
<p>
Some text here
</p>
</div>
</x-text-with-heading>呈现的HTML (问题是标题和测试显示为父div的属性)
<div class="m-4" title="Aircrafts" id="aircrafts" test="whatever $test is">
<a href="#aircrafts">
<h4 class="text-turquoise-500 font-semibold">
Aircrafts
</h4>
</a>
<div class="flex">
<p>
Some text here
</p>
</div>
</div>问题是$attributes->merge(['class' => "m-4"])还会将test="whatever $test is"和title="Aircraft"添加到呈现的html中。因此,如果$test不是字符串,它将导致一个错误,它还添加了一个我不想要的标题属性。
是否有一种方法可以从:包中排除以$attributes开头的属性,就像在不包括:message的laravel中的示例中所显示的那样?
发布于 2022-10-29 07:55:25
您可以使用:检索和过滤属性
您可以使用
filter方法筛选属性。该方法接受一个闭包,如果希望将属性保留在属性包中,则应该返回true: { $attributes->filter(fn ($value,$key) => $key == 'foo') }
例如:
text-with-heading.blade.php
<div {{ $attributes->merge(['class' => "m-4"])->filter(fn ($value, $key) => !in_array($key, ['title', 'test'])) }}>
<a href="#{{$attributes->get('id')}}">
<h4 class="text-turquoise-500 font-semibold">
{{ $title }}
</h4>
</a>
{{ $slot }}
</div>汇编成:
<div class="m-4" id="aircrafts">
<a href="#aircrafts">
<h4 class="text-turquoise-500 font-semibold">
Aircrafts
</h4>
</a>
<div class="flex">
<p>
Some text here
</p>
</div>
</div>https://stackoverflow.com/questions/74242192
复制相似问题