duanlie3187 2016-11-01 15:20
浏览 28
已采纳

在树枝的循环中只显示一次

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

</div>
  • 写回答

1条回答 默认 最新

  • dsvjw20866 2016-11-01 15:52
    关注

    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 %}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 SQL Server下载
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求