문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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

use

{% if res.website != "none" %}
    <img src="{{ asset('bundles/foo/images/web-icon.png') }}" />
{% endif %}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top