django从主模板

时间:2016-06-18 12:12:36

标签: python django

我已在项目中集成了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>

有没有优雅的方法来做到这一点?

2 个答案:

答案 0 :(得分:2)

使用assignment_taginclusion_tag

Templatetag

# 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>

创建了占位符并添加了该插件。