您不会在 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 %}