Pergunta

I am having a hard time comparing strings in a Twig template. The following example always evaluates to true, even though the res.website clearly contains the string none which should make the if statement evaluate to false.

Any ideas why this is happening and how to get it evaluate to true only when the string is not equal to none?

Many thanks in advance!

   {{res.website}}//output: none

Twig (evaluates to true!)

{% if "{{res.website}}" != "none" %}
    <img src="{{ asset('bundles/foo/images/web-icon.png') }}" />
{% endif %}

Note: when I remove the quotes from around the if "{{ ... }}" I get the following error:

A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses

Foi útil?

Solução

Enclosing your variable with double quotes will definitely not give the expected result. It will simply treat {{res.website}} as a string and compare it with none.

Simply write:

{% if res.website != "none" %}
    <img src="{{ asset('bundles/foo/images/web-icon.png') }}" />
{% endif %}

If you still have an error, make sure res is a valid variable in the current scope.

Outras dicas

Inside {% %} no need to enclose the variable {{ }}

use

{% if res.website != "none" %}
    <img src="{{ asset('bundles/foo/images/web-icon.png') }}" />
{% endif %}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top