我已在项目中集成了djangocms blog。在主页边栏我想显示最新的博客文章。问题是,我的主页是django-cms页面,我无法获得博客文章对象。 urls.py:
urlpatterns = i18n_patterns('',
url(r'^admin/', include(admin.site.urls)),
.....
url(r'djangocms_blog/', include('djangocms_blog.urls', namespace='djangocms_blog')),
url(r'^', include('cms.urls')),
)
不知怎的,在main.html我应该可以获得博客记录:
{% extends "base.html" %}
<nav class="secondary-menu">
<ul class="nav">
<!-- i need display them here -->
</ul>
</nav>
有没有优雅的方法来做到这一点?
答案 0 :(得分:2)
使用assignment_tag
或inclusion_tag
:
# templatetags/blog_tags.py
from django import template
from djangocms_blog.models import Post
register = template.Library()
@register.assignment_tag()
def latest_posts_as(limit=5):
return Post.objects.order_by('-date_published')[0:limit]
@register.inclusion_tag('latest_posts.html', takes_context=True)
def latest_posts_inline(context, limit=5):
qs = Post.objects.order_by('-date_published')[0:limit]
context.update({'posts': qs})
return context
<!-- latest_posts.html -->
{% for post in posts %}
<p>{{ post }}</p>
{% endfor %}
<!-- your_template.html -->
{% load blog_tags %}
<div>
<!-- using assignment_tag -->
{% latest_posts_as limit=20 as posts %}
{% for post in posts %}
<p>{{ post }}</p>
{% endfor %}
<!-- using inclusion_tag -->
{% latest_posts_inline limit=10 %}
</div>
limit
是可选的 - 但可能很方便:)
答案 1 :(得分:0)
想出其他解决方案。创建了新的django-cms插件:
class BlogLatestEntriesPluginNav(BlogLatestEntriesPlugin):
name = _('Navigition latest blog entries')
render_template = 'latest_entries_nav.html'
plugin_pool.register_plugin(BlogLatestEntriesPluginNav)
其中BlogLatestEntriesPlugin
是来自djangocms_blog app的插件。并创建了新模板'latest_entries_nav.html'
。然后在main.html
<ul class="nav">
{% placeholder "left_sidebar" %}
</ul>
创建了占位符并添加了该插件。