简体   繁体   中英

Display something only once in a loop in twig

I have some pics that I want to display by months.

But I my code I get the month on top of every pics.

How to avoid this ?

 {% for media in medias %} {% if media.date|date("m") == 10 and media.assetpath is not null %} <h2>Photos october</h2> <div class="col-xs-2"> <img class="img-responsive" src="{{ asset(media.assetpath) }}"/> </div> {% elseif media.date|date("m") == 11 and media.assetpath is not null %} <h2>Photos november</h2> <div class="col-xs-2"> <img class="img-responsive" src="{{ asset(media.assetpath) }}"/> </div> {% else %} <h2>other month</h2> <div class="col-xs-2"> <img class="img-responsive" src="{{ asset(media.assetpath) }}"/> </div> {% endif %} {% endfor %} 

Assuming that medias is an array sorted by date, the problem can be solved using a temporary variable:

{% set last_month = '' %}
{% for media in medias %}
  {% set month = media.date('F')|lower %}
  {% if last_month and month != last_month %}
    <h2>Photos {{ month }}</h2>
  {% endif %}
  {% set last_month = month %}

  <div class="col-xs-2">
    <img class="img-responsive" src="{{ asset(media.assetpath)  }}"/>
  </div>
{% endfor %}

However, I would rather generate a more appropriate structure, eg:

$media = [
  'November' => [
    [ /* media 1 */],
    [ /* media 2 */],
    // ...
  ],
  // ...
];

With this structure, the template code will look much cleaner:

{% for month, media in medias %}
  <h2>Photos {{ month }}</h2>
  {% for m in media %}
  <div class="col-xs-2">
    <img class="img-responsive" src="{{ asset(m.assetpath) }}"/>
  </div>
  {% endfor %}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM