Setting a boolean attribute in QWeb template

Viewed 331

I am having problems using the QWeb engine and boolean HTML attributes.

I know that in the QWeb rendering engine I can use t-attf-{attribute name} in order to set the value of attribute name to the format string. The problem is that there is no documented way (or at least I am unable to find it in the documentation) how to set a boolean attribute depending on an expression or a variable from the context.

The problem is that when using boolean attributes:

If a boolean attribute is present, its value is true, and if it's absent, its value is false.

So I cannot use t-attf-checked as using t-attf-checked="" will put checked="" inside the tag. The following will also evaluate to true as the simple appearance of the tag in the tag will evaluate to true:

  • checked=""
  • checked="0"
  • checked="false"

For example, let's say I have a radio list with multiple inputs and a variable in the context called elem_num. Depending on the value of elem_num an input of the radio list should have the boolean attribute checked.

<input class="custom-control-input" type="radio" t-attf-name="radio-1" t-attf-id="radio-1" value="1"/>
<input class="custom-control-input" type="radio" t-attf-name="radio-2" t-attf-id="radio-2" value="2"/>
<input class="custom-control-input" type="radio" t-attf-name="radio-3" t-attf-id="radio-3" value="3"/>

When elem_num == 0 the first radio button should be checked, when elem_num == 1 the second one and when elem_num == 2 the third one should be.

How can I achieve this without involving any JavaScript code? I am using Odoo 14.

Any help is appreciated.

1 Answers

You can use t-att=mapping conditionally to define the checked attribute

From QWeb Templates attributes documentation:

t-att=mapping
   if the parameter is a mapping, each (key, value) pair generates a new attribute and
   its value

Example:

t-att="elem_num==1 and {'checked': ''} or {}"
Related