Saš*_*aba 6 python django templates
我有两个块使用相同的变量调用相同的方法.我想只调用一次该方法,但结果就是块外标记的范围.我尝试在父模板中header.html使用with标记调用此方法,但似乎没有任何效果.
这是布局:
{% extends "header.html" %}
{% load navigation_tags %}
{% block header %}
{% get_section site=site as section %}
{% include "foobar.html" with section=section %}
{% endblock header %}
{% block navigation %}
<nav>
<div class="container">
{% get_section site=site as section %}
{% navigation section.slug %}
</div>
</nav>
{% endblock navigation %}
Run Code Online (Sandbox Code Playgroud)
navigation_tags.py
@register.assignment_tag
def get_parent_section(site):
if site.id == settings.FOOBAR_SITE_ID:
section = Section.objects.get(id=settings.FOOBAR_SECTION_ID)
else:
# This is also a section instance.
return site.default_section
Run Code Online (Sandbox Code Playgroud)
正如2pacho在另一个答案中和Fernando Cezar在评论中提到的,在不同部分之间共享值的最简单方法是在模板上下文中设置它。如果您使用渲染快捷方式功能,则可以传递 adict作为上下文参数,以向模板的渲染上下文添加值。这将是添加它的好地方,这将是最容易放置它的地方。
return render(request, 'template.html', {'section': get_parent_section(site)})
Run Code Online (Sandbox Code Playgroud)
但是,如果由于某种原因,您无法将其包含在上下文中,则可以使用装饰器向函数添加记忆功能,以便它将缓存计算结果,并在使用相同参数调用时立即返回。您可以使用functools.lru_cache这样做,或者django.utils.lru_cache.lru_cache如果您使用的是 Python 2.x,则它是 Django 向后移植。
@register.assignment_tag
@functools.lru_cache()
def get_parent_section(site):
if site.id == settings.FOOBAR_SITE_ID:
section = Section.objects.get(id=settings.FOOBAR_SECTION_ID)
else:
# This is also a section instance.
return site.default_section
Run Code Online (Sandbox Code Playgroud)