我正在开发一个由几个半静态页面(主页,关于等)和博客组成的Wagtail项目。在主页中,我想列出最新的博客条目,我可以将以下代码添加到HomePage模型中:
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
但是,我还想在页脚中添加最后3个条目,这是网站中所有页面的常见元素。我不确定最好的方法是什么 - 当然我可以为所有模型添加类似的代码,但也许有一种方法可以扩展Page类作为一个整体或以某种方式添加“全局”上下文?这样做的最佳方法是什么?
答案 0 :(得分:6)
对于custom template tag来说,这听起来很合适。
这个地方的好地方是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}
您需要在blog/templates/blog/includes/blog_posts.html
为此添加部分模板。然后在每个必须包含此页面的页面模板中,包含在顶部:
{% load blog_tags %}
并在所需位置:
{% latest_blog_posts %}
我注意到您的代码注释表明您想要给定页面的后代,但您的代码并没有这样做。我已将此包含在我的示例中。此外,我使用了包含标记,因此您不必在使用此自定义模板标记的每个页面模板上重复博客列表的HTML。