Globally getting context in Wagtail site

Viewed 986

I am working on a Wagtail project consisting of a few semi-static pages (homepage, about, etc.) and a blog. In the homepage, I wanted to list the latest blog entries, which I could do adding the following code to the HomePage model:

def blog_posts(self):
    # Get list of live blog pages that are descendants of this page
    posts = BlogPost.objects.live().order_by('-date_published')[:4]

    return posts


def get_context(self, request):
    context = super(HomePage, self).get_context(request)
    context['posts'] = self.blog_posts()
    return context

However, I would also like to add the last 3 entries in the footer, which is a common element of all the pages in the site. I'm not sure of what is the best way to do this — surely I could add similar code to all the models, but maybe there's a way to extend the Page class as a whole or somehow add "global" context? What is the best approach to do this?

1 Answers

This sounds like a good case for a custom template tag.

A good place for this would be in blog/templatetags/blog_tags.py:

import datetime
from django import template
from blog.models import BlogPost

register = template.Library()

@register.inclusion_tag('blog/includes/blog_posts.html', takes_context=True)
def latest_blog_posts(context):
    """ Get list of live blog pages that are descendants of this page """
    page = context['page']
    posts = BlogPost.objects.descendant_of(page).live().public().order_by('-date_published')[:4]

    return {'posts': posts}

You will need to add a partial template for this, at blog/templates/blog/includes/blog_posts.html. And then in each page template that must include this, include at the top:

{% load blog_tags %}

and in the desired location:

{% latest_blog_posts %}

I note that your code comment indicates you want descendants of the given page, but your code doesn't do that. I have included this in my example. Also, I have used an inclusion tag, so that you do not have to repeat the HTML for the blog listing on each page template that uses this custom template tag.

Related