6

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
mathiascg
  • 550
  • 1
  • 5
  • 15

1 Answers1

6

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.

nimasmi
  • 3,978
  • 1
  • 25
  • 41
  • Thanks! This works like a charm. Since there will be only one "blog index", all BlogPost should be descendant of this index, that's why I didn't include it. – mathiascg Sep 22 '17 at 13:37
  • @nimasmi does wagtail have any of it's own method or process to solve this? – w411 3 Apr 07 '19 at 08:11