我有两个 block 使用相同的变量调用相同的方法。我只想调用该方法一次,但结果超出了 block 标记的范围。我尝试在父模板 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 %}
导航标签.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
最佳答案
如 2pacho 所述在另一个答案和Fernando Cezar在评论中,在不同部分之间共享值的最简单方法是在模板上下文中设置它。如果您使用 render快捷函数,您可以将 dict
作为 context 参数传递给模板的呈现上下文添加值。那将是添加它的好地方,这将是放置它的最简单的地方。
return render(request, 'template.html', {'section': get_parent_section(site)})
但是,如果由于某种原因,你不能将它包含在上下文中,你可以使用装饰器来添加memoization。到您的函数,以便它会缓存计算结果并在使用相同参数调用时立即返回它。您可以使用 functools.lru_cache
这样做,或者如果您使用的是 Python 2.x,则它是 django.utils.lru_cache.lru_cache
的 Django backport。
@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
关于python - Django 模板中两个 block 之间的可变上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51362314/