jadu/twig-attribute-parser

将属性数组转换为HTML格式属性,以便在HTML元素中使用。

1.0.0 2023-09-19 09:14 UTC

This package is auto-updated.

Last update: 2024-08-28 11:09:30 UTC


README

将属性数组转换为HTML格式属性,以便在HTML元素中使用。

可选的 tag 属性还会生成所需的HTML元素,并在Twig视图中根据上下文切换元素时很有用。

输出始终以空格开头,以避免在未传递属性到标记时出现不必要的空格。

示例

{%
    set arrayToProcess = ['slim': 'shady', 'marshall': 'mathers', 'eminem': true, 'class': 'wrapper']
%}

<span{{ attributes(arrayToProcess) }} />

{# output: <span slim="shady" marshall="mathers" eminem class="wrapper" /> #}

布尔属性

布尔属性值将只输出键。如果存在可选的 tag,则 disabled 布尔属性的行为是上下文相关的(见下文)。

{%
    set arrayToProcess = ['foo': true]
%}

<span{{ attributes(arrayToProcess) }} />

{# output: <span foo /> #}

禁用属性

仅在特定元素上,禁用属性才有效。如果您尝试传递一个没有有效 tag 或不支持禁用属性的标签的布尔 disabled 属性,它将输出一个 is-disabled 类,您可以适当进行样式设计。

{%
    set arrayToProcess = ['disbled': true]
%}

<span{{ attributes(arrayToProcess) }} />

{# output: <span class="is-disabled" /> #}

如果同时存在 class 属性,则类列表将适当合并。如果类列表中包含 is-disabled,则不会重复。

{%
    set arrayToProcess = ['class': 'foo', 'disbled': true]
%}

<span{{ attributes(arrayToProcess) }} />

{# output: <span class="foo is-disabled" /> #}

如果 tagbuttonfieldsetinputoptionselecttextareadiv,则将输出禁用属性。

{%
    set arrayToProcess = ['disbled': true]
%}

{# note the absence of the element here, we let the attribute parser output it #}
<{{ attributes(arrayToProcess, {'tag': ('button')}) }} />

{# output: <button disabled /> #}

如果您想输出 disabled class="disabled",您需要将两个属性都传递到数组中。

如果 taga,它将添加一个 aria-disabled 属性,这是基于对无障碍性选择的意见。

{%
    set arrayToProcess = ['disbled': true]
%}

<{{ attributes(arrayToProcess, {'tag': ('a')}) }} />

{# output: <a aria-disabled="true" /> #}

HTML 实体

HTML 实体将被正确引用以适应HTML标记,这允许在工具提示等之后渲染嵌入的HTML。

{%
    set arrayToProcess = ['foo': '<span>bar</span> <blink>baz</blink>']
%}

<span{{ attributes(arrayToProcess) }} />

{# output: <span foo="&lt;span&gt;bar&lt;/span&gt; &lt;blink&gt;baz&lt;/blink&gt;" /> #}

空值

空值将被删除。如果您只想显示键,请使用布尔值。

{%
    set arrayToProcess = ['foo': '']
%}

<span{{ attributes(arrayToProcess) }} />

{# output: <span /> #}

嵌套/多维数组

不支持。