[英]Bootstrap styling in Django
Mostly is see CSS / HTML in bootstrap we came across the following template. 通常是在引导程序中看到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>
How we can achieve this behavior in the Django templates? 我们如何在Django模板中实现此行为? I mean when we are iterating over a list of values how we can keep track we need to start a new
.row
? 我的意思是,当我们遍历值列表时,如何跟踪我们需要启动一个新的
.row
?
Check the loop iteration count and do integer manipulation to check if we new .row
element should be started. 检查循环迭代计数并进行整数操作以检查是否应启动新的
.row
元素。
Thoughts? 思考?
This works: 这有效:
{% for obj in objects %}
{% if not forloop.counter|divisibleby:2 and forloop.last %}
<div class="row">
<div class="col-md-6">
{{ obj }}
</div>
</div>
{% elif not forloop.counter|divisibleby:2 %}
<div class="row">
<div class="col-md-6">
{{ obj }}
</div>
{% elif forloop.counter|divisibleby:2 %}
<div class="col-md-6">
{{ obj }}
</div>
</div>
{% endif %}
{% endfor %}
This solution uses Django built-in tags and filters. 此解决方案使用Django内置标签和过滤器。 You may consider creating a custom tag, but that goes beyond the scope of the question.
您可以考虑创建自定义标签,但这超出了问题的范围。
Django: For Loop , Custom Tags Django: For循环 , 自定义标签
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 %}
You could also split the list into chunks before sending it to the template. 您也可以在将列表发送到模板之前将其拆分为多个块。
More on how to split lists into chunks here: 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 %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.