9

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?

3 Answers 3

14

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.

5
  • 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/…) Commented Feb 12, 2017 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. Commented Feb 12, 2017 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. Commented Feb 12, 2017 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? Commented Feb 12, 2017 at 23:10
  • 1
    Answer updated. Commented Feb 13, 2017 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 %}

1

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

Source

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.