Giovanni Benussi
Giovanni Benussi

Reputation: 3530

Get child pages of specified type in Wagtail (or Django)

I have the following code to get the child pages of the current one:

{% for subpage in self.get_children %}
    ...
{% endfor %}

This is used, for example, to show a gallery of images (each children page have an image).

However, this works fine when only I have one type of children, but, when I try to add another child page (for example to show testimonials), the code above doesn't filter for children type ..so it shows all childs.

I want to know if there is another way to make this work or if my approach is wrong (the use of children pages).

Any help would be appreciated :-)

Upvotes: 10

Views: 9460

Answers (2)

gasman
gasman

Reputation: 25292

It's often easier to do these kinds of queries in Python code, rather than inside the template. Wagtail page objects provide a get_context method where you can set up additional variables to be passed into the template:

class GalleryIndexPage(Page):
    # ... field definitions here ...

    def get_context(self, request):
        context = super(BlogIndexPage, self).get_context(request)
        context['image_pages'] = self.get_children().type(ImagePage)
        return context

In this code, type is one of the methods Wagtail provides for filtering a queryset - see Page QuerySet reference for the full list.

With this method defined, you can then access the variable image_pages within your template:

{% for subpage in image_pages %}
    ...
{% endfor %}

Upvotes: 19

ozren1983
ozren1983

Reputation: 1951

There are two ways you can solve this.

First one is to filter your subpages in your view by type, e.g.:

page = Page.objects.get(slug='current-page')
pages_with_images = Page.objects.filter(parent=page, type='image')
pages_with_testimonials = Page.objects.filter(parent=page, type='testimonial')

Then, in your template, you can separately iterate through pages_with_images and pages_with_testimonials:

{% for subpage in pages_with_images %}
    ...
{% endfor %}

{% for subpage in pages_with_testimonials %}
    ...
{% endfor %}

The second solution is to check type of the subpage in your template:

{% for subpage in self.get_children %}
    {% if subpage.type == 'image' %}
        ...
    {% endif %}
{% endfor %}

Upvotes: 3

Related Questions