首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何防止Laravel组件$attributes包含传入的变量,以:

如何防止Laravel组件$attributes包含传入的变量,以:
EN

Stack Overflow用户
提问于 2022-10-29 01:13:55
回答 1查看 51关注 0票数 1

我正在尝试在我的组件(如https://laravel.com/docs/9.x/blade#default-merged-attributes )中使用laravel属性。在本例中,:message变量不包含在$attribute列表中,而是包含在启动wiht的代码属性中(我不希望它们)。这是代码和输出。

text-with-heading.blade.php

代码语言:javascript
复制
<div {{ $attributes->merge(['class' => "m-4"]) }}>
    <a href="#{{$attributes->get('id')}}">
        <h4 class="text-turquoise-500 font-semibold">
            {{ $title }}
        </h4>
    </a>
    {{ $slot }}
</div>

刀片文件调用组件

代码语言:javascript
复制
<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的属性)

代码语言:javascript
复制
<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中的示例中所显示的那样?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-29 07:55:25

您可以使用:检索和过滤属性

您可以使用filter方法筛选属性。该方法接受一个闭包,如果希望将属性保留在属性包中,则应该返回true: { $attributes->filter(fn ($value,$key) => $key == 'foo') }

例如:

text-with-heading.blade.php

代码语言:javascript
复制
<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>

汇编成:

代码语言:javascript
复制
<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>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74242192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档