您可以创建一个include模板(它不需要模型)-让我们命名它
truncated_blog_post.html
-然后可以在
index_page.html
样板这将是推荐的方法,因为使用包含模板可以在任何需要显示(通常被截断)帖子列表的地方使用它:例如,当您希望帖子位于某个标签下时。
truncated_blog_post.html
{% load wagtailcore_tags %}
<article>
<a href="{% pageurl blog %}"><h2>{{ blog.title }}</h2></a>
<p>{{ blog.date }}</p>
<p>{{ blog.body|truncatewords:40 }}</p>
</article>
使用
pageurl
标签来自
wagtailcore_tags
你会得到那篇博客文章的相对URL。显然,如果您不想为截短的帖子创建包含模板,可以将
article
代码来自
blog_post.html
直接在for循环中
index_page.html
样板
而你的
index_page.html
模板:
....
{% for blog in blogs %}
{% include "path/to/includes/truncated_blog_post.html" %}
{% empty %}
No posts found
{% endfor %}
....
为此,您必须修改
IndexPage
型号:
class IndexPage(Page):
intro = RichTextField(blank=True)
@property
def blogs(self):
blogs = BlogPage.objects.live()
return blogs
def get_context(self, request):
# Get blogs
blogs = self.blogs
# Update template context
context = super(IndexPage, self).get_context(request)
context['blogs'] = blogs
return context
content_panels = Page.content_panels + [
FieldPanel('intro', classname='full'),
]
subpage_types = ['blog.BlogPage']