在嵌套的 Laravel 7 Blade 组件中分配 $attributes

4

在Laravel 7中,我开始使用视图组件(View Components)。 我正在尝试像这样从一个组件将$attributes变量传递到另一个组件中:

x-modal组件:

<div {{ $attributes->merge(['class' => 'modal fade']) }}>
   Something great...
</div>

<x-modal {{ $attributes }}>
    Something great too
</x-modal>

在这种情况下,我在x-modal组件中有一个id属性,如下所示:
<x-modal-form id="aRandomId" title="Test"></x-modal-form>

但在这种情况下,id aRandomId 没有传递到x-modal组件。由于{{ $attributes }}出现错误"syntax error, unexpected 'endif' (T_ENDIF), expecting end of file"。 你知道该怎么做吗?

你想在同一个视图中重复ID吗?! - IBRAHIM EZZAT
我在一个组件中使用另一个组件,并且我想将ID传递到最深层的组件。 - Pythagus
2个回答

1
此问题已在 Laravel 8 中得到修复:#32576 现在您可以将 $attributes 变量从一个组件传递到另一个组件。

0
根据 Laravel 文档

所有不属于组件构造函数的属性都会自动添加到组件的“属性包”中。通过 $attributes 变量,这个属性包会自动提供给组件。这个变量可以在组件内输出,渲染出所有的属性。

如果在一个视图中使用多个嵌套组件或者想要使用属性包,需要将共有的属性放入属性包中,手动为每个组件添加独特的属性,如下:

<x-modal {{ $attributes }}>
    <x-modal-form {{ $attributes }} id="aRandomId" title="Test">
     // code here
    </x-modal-form>
</x-modal>

当然,id 属性为 HTML 元素指定唯一的标识符。id 属性的值在 HTML 文档中必须是唯一的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接