How do I compare two strings in a template file? The template file I am using contains the following code.

foo is '{{ foo }}'
item.url is '{{ item.url }}'
{% if item.url == foo %}
  equal
{% 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 &lt;div class="something"&gt;content...&lt;/div&gt;. But when you do a dump or kint, you will see that content is an array, and doing a comparision {% if content = '&lt;div class="something"&gt;content...&lt;/div&gt;' %} 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' %}.