问题
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>
Here is my code:
{% 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 %}
回答1:
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 %}
来源:https://stackoverflow.com/questions/21624845/why-is-django-template-loop-nesting-my-divs