The template file I am using contains the following code.

foo is '{{ foo }}'
item.url is '{{ item.url }}'
{% if item.url == foo %}
{% endif %}

I was expecting this code to output foo is 'test' item.url is 'test' equal, but instead it outputs foo is 'test' item.url is 'test'; the equal part doesn't appear.

The following code works.

{% if 'test' == 'test' %}

This code doesn't work.

{% if item.url == 'test' %}

Why doesn't the code I am using work?


This depends on the context, but most likely item.url is not a native string variable test, but a function or a render array with the string representation / render result test.

This is similar to Drupal's well known content variable: When you render {{ content }}, you will get the string representation like <div class="something">content...</div>. But when you do a dump or kint, you will see that content is an array, and doing a comparision {% if content = '<div class="something">content...</div>' %} will be false too.

I'd recommend to always avoid boolean operations with rendered representations, always head for the raw data. E.g. don't do {% if content.field_something.0 == 'my_value' %}, instead inspect the entity {% if node.field_something.0.value == 'my_value' %}.

If you have to compare to a render array, you could do somehting like {% if some_var|render == 'my_string' %}.

  • Awesome, thanks for the help. Adding |render works great.
    – Innovine
    Oct 4 '19 at 11:23

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.