wagtailwagtail-snippet

Using Wagtail Collections for Images via Snippet, how do you iterate through them for display in templates?


I have a site that uses a lot of images (a page can range from 12-40 subject to requirements). User experience of adding a single image at a time using the ImageChooserPanel is rather poor. I think adding all images to a collection and then applying said collection to a Page makes a lot of sense.

Having searched here, in principle I like the solution provided by @kalob-taulien: How to give user option to select a wagtail collection of images in page? (tldr; add collections as a snippet and use a SnippetChooserPanel to select the relevant collection)

I've looked at the one linked to by gasman, but that doesn't make as much sense to me (contextually - I'm really new at this). Saying that, I'm struggling with utilising the solution I've linked to. If you add collections exactly as Kalob says, how do you then iterate through those images in a template for display?

I'm new to Django/Wagtail, so I may be wording that poorly. To put it in to context, using the ImageChooserPanel method of adding images, I would do this:

{% for item in page.gallery_images.all %}
   {% image item.image width-352 format-jpeg as item_352 %}
   ...

How do I do the same for the Collection containing images? I've tried page.collection, guessed at page.collection.image(s), and a fair few more; I just can't seem to workout how to access the images.


Solution

  • OK, so I eventually figured it out. I don't know why I didn't think of this yesterday! Apologies to anyone who wasted time on this.

    I'll share my solution in case anyone else is interested, though if you think of a more efficient way please still share it. This works, but I suspect this is quite uneconomical.

    I added context to my model (which was based on the post linked in my question):

    from wagtail.images.models import Image
    
    class CustomPage(Page)
       ...
       def get_context(self, request):
          context = super().get_context(request)
          images = Image.objects.filter(collection=self.collection)
    
          context['images'] = images
          return context
       ...
    

    My template image rendition now looks really simple:

       ...
       {% for item in images %}
          {% image item width-352 format-jpeg as item_352 %}
          ...
    

    The result is, user experience is improved. Now, we create a collection, drop all image files in one go into that collection (as a singular multi-upload) and select said collection in the page. I think this is as close as I can get to a 'gallery upload' solution at this time. Alternatives very welcome.