Tom Good Tom Good - 1 month ago 5
Twig Question

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 %}




Answer

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, e.g.:

$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 %}
Comments