【问题标题】:Why is Django template loop nesting my divs?为什么 Django 模板循环嵌套了我的 div?
【发布时间】:2014-03-04 16:38:37
【问题描述】:

我正在将 Bootstrap 与 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 %}

【问题讨论】:

    标签: django twitter-bootstrap if-statement django-templates nested-loops


    【解决方案1】:

    您可能需要删除下面显示的行中多余的&lt;div&gt;

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

    【讨论】:

    • 我试过这个,我的 div 仍然没有排队。他们是惊人的。这可能是由于此模板之前有一个额外的或未关闭的 div 造成的,还是我的逻辑有问题?
    • 现有的逻辑看起来太复杂了,很可能某处多了一个div。
    猜你喜欢
    • 2019-09-09
    • 1970-01-01
    • 2012-10-25
    • 2020-11-07
    • 2012-06-11
    • 2012-12-01
    • 2023-03-21
    • 2020-08-03
    • 1970-01-01
    相关资源
    最近更新 更多