7

field_boolean is a boolean field.

{% if content.field_boolean == true %} or {% if content.field_boolean == 1 %} or {% if content.field_boolean == 'true' %} or {% if content.field_boolean == '1' %} don't work.

How do I test if the checkbox is checked?

12

You want to look at the raw value, not the render array.

Example:

{% if node.field_foo is not empty %}

This checks if the field exists. The render array won't be useful beyond rendering values.

Don't look at content - that is simply the render array. Look at the fields in your entity object (node, paragraph, etc). You might want to install Twig XDebug to breakpoint your templates or inspect variables in mytheme.theme.

You should be able to look at {% if node.field_foo.value ... %} for equality checking.

  • How do I check the raw value? 'content.field_boolean.value' doesn't seem to work. Also see my other question about rendering raw values (drupal.stackexchange.com/questions/228388/…) – Pim Feb 12 '17 at 22:59
  • 3
    Don't look at 'content'. Look at the fields in your entity object (node, paragraph, etc). You might want to install Twig xdebug to breakpoint your templates or inspect variables in mytheme.theme. – Kevin Feb 12 '17 at 23:03
  • Thank you very much! That solved the question. If you want to post the same answer to the other question, that might be helpful to other users. Otherwise I'll answer it myself. – Pim Feb 12 '17 at 23:09
  • Just another question: is it more efficient to directly use node.field or paragraph.field instead of content.field aside the twig template? – Pim Feb 12 '17 at 23:10
  • 1
    Answer updated. – Kevin Feb 13 '17 at 2:57
1

Here is how I solved this, it requires the twig_field_value project.

For the boolean field, set the on and off values to 1 and 0 respectively.

In twig:

{% if content.field_foo|field_raw('value')|number_format(0,'.',',') is same as('0') %} <span>the box is NOT checked</span> {% endif %}

0

This works for me.
{% if '1' in content.field_name.0 %} {{ "anything" }} {% endif %}

Source

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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