gpt4 book ai didi

python - django 从主模板中的外部应用程序获取上下文

转载 作者:行者123 更新时间:2023-11-28 17:27:09 25 4
gpt4 key购买 nike

我已经整合了djangocms blog在我的项目中。在主页侧边栏中,我想显示最新的博客文章。问题是,我的主页是 django-cms 页面,我无法获取博客文章对象。网址.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>

有什么优雅的方法可以做到这一点吗?

最佳答案

使用 assignment_taginclusion_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 是可选的 - 但可能很方便:)

关于python - django 从主模板中的外部应用程序获取上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37896785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com