Impostazione di attributi booleani senza valore con la funzione tag

Aug 20 2020

Quando si utilizza la funzione tag , come si gestiscono attributi privi di valore che potrebbero anche essere nulli?

Ad esempio, è fantastico che possiamo fare ...

{% set idVar   = 'idstring' %}
{% set nameVar = 'namestring' %}
{% set typeVar = 'typestring' %}

{{ tag('input', {
    id: idVar,
    name: nameVar,
    type: typeVar
}) }}

…generare:

<input id="idstring" name="namestring" type="typestring">

Ma cosa succede se l' requiredattributo è anche una variabile? Non possiamo fare:

{% set reqVar  = '' %}

{% if field is required %}
    {% set reqVar = 'required' %}
{% endif %}

{{ tag('input', {
    id: idVar,
    name: nameVar,
    required: reqVar
}) }}

... perché se reqVarè vuoto, si vorrebbe che l' requiredattributo non fosse scritto affatto. Generare:

<input id="idstring" name="namestring" type="typestring">

... e non :

<input id="idstring" name="namestring" type="typestring" required>

La stessa cosa si applica ad altri attributi booleani come hidden.

C'è un modo per farlo con questa funzione? Cosa mi manca o non ricevo?

Risposte

4 BrandonKelly Aug 20 2020 at 00:59

Se un attributo è impostato su true, verrà aggiunto senza un valore.

{{ tag('input', {
    id: idVar,
    name: nameVar,
    required: true
}) }}

Inoltre, se è impostato su nullo false, verrà omesso, come se non fosse mai stato elencato per primo.