Вопрос

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