我知道有上下文处理器可以做到这一点,但我想在模板标签中设置全局模板变量。到目前为止,我试过这个:
class SetNode(template.Node):
def __init__(self, key, nodelist):
self.key = key
self.nodelist = nodelist
def render(self, context):
value = self.nodelist.render(context)
for d in context.dicts:
d[self.key] = value
return ''
即。迭代所有上下文并设置变量,但它不起作用。任何人都可以解释如何做到这一点?例如,base.html:
{{ my_var }} {# I want to set this variable in child template #}
{% block content %}
{% endblock %}
child.html:
{% extends 'base.html' %}
{% block content %}
{% set my_var %}Hello{% endset %}
{% endblock %}
有可能吗?