首页 > 解决方案 > 我可以使用 Django 中的中断模板标签吗

问题描述

我正在运行 for 循环来查找图像,但我想在找到图像后阻止 for 循环。

我发现这个网站似乎可以解决我的问题,但似乎没有针对 Django 1.10.5 进行更新:https ://djangosnippets.org/snippets/2093/ 。

{% for article in object_list %}
    {% if article.get == true %}
        <div id="tagHeader" style="background: url({{ article.get_thumbnails|varkey:'grid_thumb' }}) no-repeat center center fixed;"><!-- background image not working becuase home_background isn't in CMS -->
    {% else %}
        <div id="tagHeader" style="background: url({% static 'publicnfx/images/baconburger.jpg' %}) no-repeat center center fixed;">
    {% endif %}
{% endfor %}

有谁知道这个的另一种解决方案?

标签: pythondjango

解决方案


通过简单地添加|slice:":1"到 for 循环的末尾,我达到了我想要的结果。一旦它从第一篇文章中抓取了第一张图片,它就停止了我的 for 循环。

{% for article in object_list|slice:":1" %}

推荐阅读