【问题标题】:How to loop through the multiple items in Django Template如何遍历 Django 模板中的多个项目
【发布时间】:2022-01-03 13:50:19
【问题描述】:

如何通过以下方式遍历 django 模板中的项目

    {% for brand in categories%}
    <div class="brand-col">
        <figure class="brand-wrapper">
            <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> (item1)
        </figure>
         <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> (item2)
        </figure>
    </div>
    {% endfor %}
    

<div class="brand-col">
        <figure class="brand-wrapper">
            <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> (item3)
        </figure>
         <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> (item4)
        </figure>
    </div>

<div class="brand-col">
        <figure class="brand-wrapper">
            <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> (item5)
        </figure>
         <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> (item6)
        </figure>
    </div>

参考:(括号内的项目编号仅供参考) 在这里,首先我想在 figure 标记上循环 1 和循环 2,然后我想在图上的 div 内循环整个 div 和循环 3 和循环 4标记

我尝试使用循环,但没有运气。任何帮助将不胜感激。

【问题讨论】:

  • 不幸的是,这个问题不够清晰。什么是第 1 项和第 2 项等?
  • 您好 Yusuf,感谢您的评论。实际上我试图将循环计数表示为 item1,依此类推

标签: django django-templates django-template-filters


【解决方案1】:

这里概述了如何实现这一点。在您的视图函数中有一个枚举对象,例如

enumerated_brands = enumerate(categories)

然后将此对象传递给render方法中的上下文变量,用于您的视图函数的return语句例如:

def brand_view(request,...):
    ...
    enumerated_brands = enumerate(categories)
    ...
    return render(..., context={'enumerated_brands': enumerated_brands})

然后,在您的 html 文件中使用 enumerated_brands:

{% for brand in brands %} 
{% if forloop.counter0|divisibleby:2 %} 
<div class="brand-col"> 
{% endif %} 
<figure class="brand-wrapper"> 
<img src="{{brand.product_feature_image.image.url}}" alt="{{brand.name}}" width="410" height="186" /> 
</figure> 
{% if forloop.counter|divisibleby:2 or forloop.last %} 
</div> 
{% endif %} 
{% endfor %}

【讨论】:

  • 我收到此错误:异常类型:TemplateSyntaxError 异常值:无法解析余数:来自 '(index+1)' 的 '(index+1)'
  • 尝试改用这个:{% if index+1|modulo:3 == 0 %}
  • 还是同样的问题:异常类型:TemplateSyntaxError 异常值:无法解析某些字符:index|+1||modulo:3
  • 我认为您输入错误。您是否复制并粘贴了我在上面编辑的回复?
  • 你也可以试试:{% if index|add:"1"|divisibleby:3 %}
猜你喜欢
  • 2011-07-16
  • 1970-01-01
  • 2015-09-03
  • 2014-03-27
  • 2019-07-14
  • 2011-05-15
  • 1970-01-01
  • 2018-06-14
  • 2023-02-26
相关资源
最近更新 更多