【问题标题】:Modify Django for loop every four iterations每四次迭代修改 Django for 循环
【发布时间】:2017-06-04 20:17:54
【问题描述】:

我有一个由 Django 生成并使用 Bootstrap 进行样式设置的日历。 这是 Django 模板中的代码:

<div class="content">
  {% for month in period.get_months %}
    <div class="col-md-3">
      <div class="row row-centered">
        <button class="btn btn-custom active" href="{% url "month_calendar" calendar.slug %}{% querystring_for_date month.start 2 %}">{{month.name}}</button>
      </div>
      <div>
        {% month_table calendar month "small" %}
      </div>
    </div>
  {% endfor %}
</div>

现在,由于月份的周数不同,它们的高度也不同,我想避免这样的事情:

我从this answer 了解到,最好的解决方案是使用clearfix

那么,如何修改模板中的 for 循环,以便 Django 每四个项目插入一个额外的行 &lt;div class="clearfix"&gt;&lt;/div&gt;

【问题讨论】:

标签: css django twitter-bootstrap


【解决方案1】:

用于循环的 Django 模板将当前索引存储在 forloop.counter 变量中。您可以在docs 中阅读有关此内容的信息。所以你可以尝试像这样改变你的代码:

<div class="content">
  {% for month in period.get_months %}
    <div class="col-md-3">
      <div class="row row-centered">
        <button class="btn btn-custom active" href="{% url "month_calendar" calendar.slug %}{% querystring_for_date month.start 2 %}">{{month.name}}</button>
      </div>
      <div>
        {% month_table calendar month "small" %}
      </div>
    </div>
    {% if forloop.counter|divisibleby:4 %}
        <div class="clearfix"></div>
    {% endif %}
  {% endfor %}
</div>

【讨论】:

  • 嗨。我对 % 符号 Django 一点也不熟悉。我尝试了你的代码,这很有意义,但我收到一个错误Could not parse the remainder: '%' from '%'
  • 您好,我的答案已修复,现在试试
  • 现在我收到错误消息'endfor', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?
  • 抱歉打错了我关闭了 if block 使用 endfor 块而不是 endif。
  • 好的,知道了,它可以工作了! (除了可能应该跳过 0 计数器,因为现在 1 月份在它自己的行中)
猜你喜欢
  • 2020-08-07
  • 2018-02-13
  • 2017-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
  • 2011-08-16
  • 2017-02-09
相关资源
最近更新 更多