2

I want to use {% if %} in a node.html.twig, but it doesn't work.

I am using this code.

{% if content.field_number == 0 %}
  zero
{% else %}
  one
{% endif %}

It always print one.

The following code always print zero.

{% if content.field_number %}
  zero
{% else %}
  one
{% endif %}

What code should I use to zero when the field contains zero?

1
  • What is the actual value of content.field_number?
    – ya.teck
    Commented Apr 15, 2016 at 9:52

1 Answer 1

4

content.field_number is the rendered output and the value of the field is somewhere inside the render array, for example in a #markup. But this will change whenever someone reconfigures the view mode.

It is better to use the node object in this case, because the field value will be available for all view mode configurations:

{% if node.field_number.value %}
  not zero
{% else %}
  zero
{% endif %}

Your Answer

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