如果条件在twig模板引擎中的for循环

时间:2013-08-21 12:36:14

标签: symfony twig

每个公司对象都与图像具有一对多的关系 现在在我的模板中,我想检查是否有类型为testtype的图像。

如何用树枝处理这件事?以下是一个例外:

  

值为“testtype”的意外标记“字符串”(“预期名称”)

枝条

{% for image in company.images if image.type is 'testtype' %}
{% endfor %}

4 个答案:

答案 0 :(得分:6)

<ul>
{% for user in users if user.active %}
    <li>{{ user.username|e }}</li>
{% endfor %}
</ul>

http://twig.sensiolabs.org/doc/tags/for.html#adding-a-condition

答案 1 :(得分:3)

new way to do that是以下(for if is deprecated since Twig 2.10):

{% for image in company.images|filter(image => image.type is 'testtype') %}
{% endfor %}

答案 2 :(得分:0)

只要testtype是一个字符串,我就会尝试:

{% for image in company.images if image.type == 'testtype' %}

答案 3 :(得分:-1)

你试过这个吗?

{% for myimage in company.images %}
   {% if myimage.type == 'testtype' %}
   {% endif %}
{% endfor %}