我想要一个夹层画廊的引导轮播。基本上;我要提取所有图像,我想单行显示三个图像。这是我真正讨厌的工作代码片段;我真的很想使它适用于无限数量的图像。
{% if page.docpage.gallery %}
<script src="{% static "mezzanine/js/magnific-popup.js" %}"></script>
<link rel="stylesheet" href="{% static "mezzanine/css/magnific-popup.css" %}">
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
{% with page.docpage.gallery.gallery.images.all as images %}
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
{% for image in images %}
{% cycle '<div class="item active">' '' '' '<div class="item">' '' '' '<div class="item">' '' ''%}
{% cycle '<div class="gallery row"><div class="col-xs-12 col-sm-12">' '' ''%}
<a class="thumbnail" rel="#image-{{ image.id }}" title="{{ image.description }}" href="{{ image.file.url }}">
<img class="img-responsive" src="{{ MEDIA_URL }}{% thumbnail image.file 200 200 %}"></a>
{% cycle '' '' '</div></div></div>'%}
{% endfor %}
</div>
</div>
{% endwith %}
{% endif %}
我基本上是遍历图像并根据需要添加其他嵌套标签。我也尝试过通过forloop.counter | divisibleby:3跟踪循环,但发现关闭div的应用不正确。
有谁对在Jinja / django / mezzanine中如何进行这项工作有任何想法?
否则,我可以整理一些JavaScript来完成工作。
谢谢
最佳答案
如您所知,尝试在模板中执行此逻辑并不理想。我建议您在视图功能中执行此操作。遵循以下原则:
# Handy function to split a list into equal sized groups,
# See http://stackoverflow.com/a/434328/3955830
def chunker(seq, size):
return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))
# Split images into groups of three
image_groups = chunker(images, 3)
# Pass image_groups to your template context.
# If in a class based view then you can do this in the
# get_context_data() method.
然后在模板中,事情变得简单得多:
{% for group in image_groups %}
<div class="item {% if forloop.first %}active{% endif %}">
<div class="gallery row">
<div class="col-xs-12 col-sm-12">
{% for image in group %}
<a class="thumbnail" rel="#image-{{ image.id }}" title="{{ image.description }}" href="{{ image.file.url }}">
<img class="img-responsive" src="{{ MEDIA_URL }}{% thumbnail image.file 200 200 %}"></a>
{% endfor %}
</div>
</div>
</div>
{% endfor %}