您不会迭代 Django-CMS 中的插件实例。占位符只是以线性方式呈现分配给它们的插件。可以将插件拖放到占位符中以重新排列它们,但据我所知,您无法在模板级别迭代插件本身,至少不容易。
要执行您想要的操作,您需要创建一个 CMS 插件,该插件允许您创建可以迭代的模型的多个实例,类似于“图像库”。
从概念上讲,您将有一个父模型:
class Gallery(CMSPlugin):
""" A model that serves as a container for images """
title = models.CharField(max_length=50, help_text='For reference only')
def copy_relations(self, oldinstance):
for slide in oldinstance.slides.all():
slide.pk = None
slide.gallery = self
slide.save()
def __unicode__(self):
return self.title
和一个子模型:
class Slide(models.Model):
def get_upload_to(instance, filename):
return 'galleries/{slug}/{filename}'.format(
slug=slugify(instance.gallery.title), filename=filename)
title = models.CharField(max_length=100)
image = models.ImageField(upload_to=get_upload_to)
alt = models.CharField(max_length=100)
gallery = SortableForeignKey(Gallery, related_name='slides')
def __unicode__(self):
return self.title
那么你就会有一个 CMS 插件,如下所示:
class CMSGalleryPlugin(CMSPluginBase):
admin_preview = False
inlines = Slide
model = Gallery
name = _('Gallery')
render_template = 'gallery/gallery.html'
def render(self, context, instance, placeholder):
context.update({
'gallery': instance,
'placeholder': placeholder
})
return context
plugin_pool.register_plugin(CMSGalleryPlugin)
最后是迭代幻灯片图像的模板:
{% for slide in gallery.slides.all %}
<img src="{{ slide.image.url }}" alt="{{ slide.alt }}" />
{% endfor %}