django中的列表:在3个项目后显示某个标记

时间:2018-02-23 06:53:54

标签: python arrays django twitter-bootstrap

我正在使用Django,我正在尝试生成Bootstrap行和列以显示数据库中的记录。在每三个记录之后,应添加一个新行。因此,如果我有9条记录,则应显示以下代码:

<div class="row">
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
</div>

<div class="row">
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
</div>

<div class="row">
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
</div>

现在我有了这段代码:

<div class="row">
{% for info in list %}
  <div class="col-lg-4">{{ info.title }}"></div>
{% endfor %}
</div>

这会产生:

<div class="row">
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
  <div class="col-lg-4">item</div>
</div>

如何在每3条记录后显示额外的行标记?

1 个答案:

答案 0 :(得分:1)

尝试使用forloop.counterdivisibleby

<div class="row">
{% for info in list %}
  <div class="col-lg-4">{{ info.title }}</div>
  {% if forloop.counter|divisibleby:"3" %}
    </div>
    <div class="row">
  {% endif %}
{% endfor %}
</div>