TransWikia.com

Setting valueless boolean attributes with the tag function

Craft CMS Asked by Jonathan Schofield on November 28, 2020

When using the tag function, how does one handle valueless attributes which could also be null?

For example, it’s great we can do…

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

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

…to generate:

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

But what about if the required attribute is also a variable? We can’t do:

{% set reqVar  = '' %}

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

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

…because if reqVar is empty, one would want the required attribute to not be written at all. To generate:

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

…and not:

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

The same thing applies to other boolean attributes like hidden.

Is there a way to do this with this function? What am I missing or not getting?

One Answer

If an attribute is set to true, it will get added without a value.

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

Also, if it is set to null or false, it will be omitted, as if it was never listed in the first place.

Answered by Brandon Kelly on November 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP