问题
I want to display a list of YouTube videos and let my user edit this list.
I thought of doing it like this:
- Make a template where this will be displayed. In this template do something like
<ul>{% for plugin in page %}<li>plugin</li>{% endfor %}</ul>
. - Make a
youtube_videos
placeholder and configure it to be limited to only that type of plugin.
But I don't know how to make this iteration over the plugin instances in the current page in the template. I didn't see anything about this in django-cms documentation and, yes, I guess that django-cms "is just django" and if I'd had known django proper then I would have figured this out already.
But a nice example here would be nice.
回答1:
You don't iterate over plugin instances in Django-CMS. Placeholders simply render the plugins that are assigned to them, in linear fashion. Plugins can be dragged-and-dropped within placeholders to re-arrange them, but to the best of my knowledge, you can't iterate over the plugins themselves at the template level, at least not easily.
To do what you want, you would need to create a CMS plugin that allows you to create multiple instances of a model that you could iterate over, similar to an "image gallery".
Conceptually, you would have a parent model:
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
and a child model:
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
then you'd have a CMS Plugin like so:
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)
and finally, the template that iterates over the slide images:
{% for slide in gallery.slides.all %}
<img src="{{ slide.image.url }}" alt="{{ slide.alt }}" />
{% endfor %}
来源:https://stackoverflow.com/questions/20324664/how-to-iterate-over-cms-plugin-instances-from-a-page-in-a-django-template