python - Django 中的 Bootstrap 样式

标签 python css django twitter-bootstrap

主要是在 bootstrap 中查看 CSS/HTML,我们遇到了以下模板。

    <div class="row">
      <div class="col-sm-6">
        # Add image/ or data you want
      </div>
      <div class="col-sm-6">
        # Add image/ or data you want
      </div>
    </div>

    # Second row

    <div class="row">
      <div class="col-sm-6">
        # Add image/ or data you want
      </div>
      <div class="col-sm-6">
        # Add image/ or data you want
      </div>
    </div>

我们如何在 Django 模板中实现此行为?我的意思是,当我们迭代值列表时,我们如何跟踪我们需要启动一个新的 .row

肮脏的解决方案

检查循环迭代计数并进行整数操作以检查是否应启动新的 .row 元素。

想法?

最佳答案

创建一个模板过滤器,用于将列表拆分为多个 block :

from django import template

register = template.Library()

@register.filter
def chunks(l, n):
    n = max(1, int(n))
    return (l[i:i+n] for i in xrange(0, len(l), n))

用法:

{% for chunk in images|chunks:2 %}
    <div class="row">
        {% for image in chunk %}
            <div class="col-sm-6">
                # Add image/ or data you want
            </div>
        {% endfor %}
    </div>
{% endfor %}

您还可以在将列表发送到模板之前将其拆分为多个 block 。

有关如何将列表拆分为 block 的更多信息,请参见此处: How do you split a list into evenly sized chunks?

填充列表的自定义过滤器:

@register.filter
def ljust_list(l, n):
    """
    ljust_list([1, 2], 4) -> [1, 2, None, None]
    """
    return l + [None] * (n - len(l))

@register.filter
def rjust_list(l, n):
    """
    rjust_list([1, 2], 4) -> [None, None, 1, 2]
    """
    return [None] * (n - len(l)) + l

用法:

{% for chunk in images|chunks:2 %}
    <div class="row">
        {% for image in chunk|ljust_list:2 %}
            <div class="col-sm-6">
                # Add image/ or data you want
            </div>
        {% endfor %}
    </div>
{% endfor %}

关于python - Django 中的 Bootstrap 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31765019/

相关文章:

python - 如何在 Elastic Beanstalk 上启动时运行一次 python 脚本

html - 在页脚中使用 float <li> 元素

css - 向 CSS 添加过渡

python - 如何在 Django 中只打印当前登录的用户数据?

python - 段错误 : 11 with Matplotlib python 2. 7.8 和 Mavericks

python - PostgreSQL 多用户应用程序

python - 如何为 selenium webdriver 设置 socks5 代理? Python

python - 从Python SDK调用时,从Azure存储 “connection reset” 10054错误中恢复的正确方法是什么?

jquery - 响应式多图像尺寸布局?

python - 为什么 Django 不重置 SQLite3 中的序列?