Why is Django template loop nesting my divs?

≯℡__Kan透↙ 提交于 2020-01-15 09:47:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!