为什么Django的模板循环嵌套我div的?(Why is Django template loop

2019-10-19 07:13发布

我使用的引导与Django和希望.item-container.col-MD-4是一个行内的三盒。 它应该是这个样子:

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

我得到更多的东西是这样的:

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

Answer 1:

你可能需要删除多余<div>在该行如下所示

   {% if forloop.counter != products|length  %}
    </div>    <----------------------- THIS
    <script> console.log('not last', {{ products|length }}, {{forloop.counter}} ); </script>
   {% endif %}

我建议你重写模板,简单的东西

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


文章来源: Why is Django template loop nesting my divs?