【问题标题】:Is there a break template tag in Django I can useDjango中是否有我可以使用的中断模板标签
【发布时间】:2019-06-22 10:50:30
【问题描述】:

我正在运行 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 %}

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

【问题讨论】:

  • 看起来应该在 Python 代码中执行。
  • 我想我将不得不这样做,我将尝试使用标签的另一种解决方案,如果可行,我会将其发布在这里,否则我将求助于 python。
  • 你会发现有用的this question
  • 我认为逻辑应该远离 Django 的模板。在视图级别限制 object_list 并解决您的问题。解析您的文件以获取背景名称并确定 object_list 长度。
  • @KyrylHavrylenko for photos in gallery.photo_set|slice:":1" 所以我使用了它并且它有效。但是如果第一张图片中没有图片,这是否意味着它只会返回空白?

标签: python django


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-01-28
    • 2011-02-03
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 2015-01-02
    • 2014-03-20
    • 1970-01-01
    相关资源
    最近更新 更多