3

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?

1 Answer 1

4

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.

3
  • Great. So the function knows which attribute names are allowed to be boolean. Presumably inherited from knowledge embedded in Yii? Commented Aug 19, 2020 at 18:37
  • Assuming I have understood correctly, it would be good if this could be noted in the docs. Commented Aug 19, 2020 at 18:38
  • 1
    The docs link to yii\helpers\BaseHtml::renderTagAttributes() which has a full description of the different types of attributes/values that are supported. Commented Oct 7, 2020 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.