为什么Django模板循环嵌套我的div? [英] Why is Django template loop nesting my divs?
本文介绍了为什么Django模板循环嵌套我的div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Bootstrap与Django,并希望.item-container.col-md-4是一行内的三个框。它应该看起来像这样:
I am using Bootstrap with Django and want the .item-container.col-md-4 to be three boxes inside a row. It should look something like this:
<div class="row">
<div class="item-container col-md-4> Stuff</div>
<div class="item-container col-md-4> Another Thing</div>
<div class="item-container col-md-4> This Next One</div>
</div>
我得到的东西更像这样:
I am getting something more like this:
<div class="row">
<div class="item-container col-md-4> Stuff
<div class="item-container col-md-4> Another Thing</div>
</div>
</div>
<div class="item-container col-md-4> This Next One</div>
这是我的代码:
{% for product in products %}
{% if forloop.first %}
<div class="row">
{% endif %}
<div class="item-container col-md-4">
{{ product.someinfo }}
</div>
{% if forloop.counter != products|length %}
</div>
<script> console.log('not last', {{ products|length }}, {{forloop.counter}} ); </script>
{% endif %}
{% if forloop.last %}
</div>
<script> console.log('by 3', {{ products|length }}, {{forloop.counter}} );</script>
{% elif forloop.counter|divisibleby:3 %}
<script> console.log('last', {{ products|length }}, {{forloop.counter}} );</script>
<div class='row'>
{% endif %}
{% empty %}
<div class="nothing-found">
Nothing found.
</div>
{% endfor %}
推荐答案
p>您可能需要删除以下行中的额外< div>
You probably need to remove the extra <div>
in the line shown below
{% if forloop.counter != products|length %}
</div> <----------------------- THIS
<script> console.log('not last', {{ products|length }}, {{forloop.counter}} ); </script>
{% endif %}
我建议您将模板重写为更简单的
I would recommend rewriting your template to something simpler
{% if products %}
<div class="row">
{% for product in products %}
<div class="item-container col-md-4"> {{ product.someinfo }} </div>
{% if forloop.counter|divisibleby:3 %}
</div>
<div class="row">
{% endif %}
{% endfor %}
</div>
{% else %}
<div class="nothing-found">
Nothing found.
</div>
{% endif %}
这篇关于为什么Django模板循环嵌套我的div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文