Twig检查多个值

时间:2016-08-26 00:33:24

标签: php templates twig

我有大约5张左右的布尔表。我想测试所有这些,如果一个或多个返回true则执行某些操作。

到目前为止,我尝试了类似

的内容
<div class="well sb">
  <div>
    <div class="product-details">
      <div class="image-video-linkmas">
        <a href="#" target="_blank">
          <img alt="#" src="http://lorempixel.com/300/300">
        </a>
        <div class="overlay">
          <div class="intro-descriptioncar">
            intro-car
          </div>
          <div class="userfield1car">
            car1
          </div>
        </div>
      </div>

    </div>
    <div class="product-title">
      product-title
    </div>
  </div>

但是,如果他们中的任何人返回true,那么它会说

{% if product.is_red == true %}

<h1>Has colors</h1>

{% elseif product.is_yellow == true %}

<h1>Has colors</h1>

{% elseif product.is_green == true %}

<h1>Has colors</h1>

{% elseif product.is_purple == true %}

<h1>Has colors</h1>

{% elseif product.is_black == true %} 


{% endif %}

无论返回的次数是多少都是如此。有没有办法检查所有这些,如果还有一个返回true,则返回&#34;有颜色&#34;?

2 个答案:

答案 0 :(得分:2)

您必须使用flag中的twig来跟踪是否指定了一种或多种颜色。一个较短的代码示例是(也应该与对象product一起使用)

{% 
    set product = {
        'is_red'     : false,
        'is_yellow'  : false,
        'is_blue'    : true,
        'is_green'   : false,
    }
%}

{% set has_color = false %}
{% for color in ['red', 'yellow', 'blue', 'green', 'purple', ] %}
   {% if product['is_'~color] is defined and product['is_'~color] %}{% set has_color = true %}{% endif %}
{% endfor %}

{% if has_color %}
<h1>Has color</h1>
{% endif %}

fiddle

答案 1 :(得分:-1)

深入挖掘Twig,我会这样做......

{% set has_color = false %}
{% for color in product if color is true %}
   {% set has_color = true %}
{% endfor %}

{% if has_color %}
<h1>Has color</h1>
{% endif %}