开发者

Set global template variable in template tag

I know that there are context processors that can do this, but I want to set global template variable in template tag. So far I tried this:

class SetNode(template.Node):
    de开发者_StackOverflow中文版f __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 ''

I.e. iterate over all contexts and set variable, but it does not work. Can anyone explain how to do this? For example, 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 %}

Is it possible at all?


Here is an oldie-but-a-goodie: the {% expr %} tag. The code is self-explanatory.

Note that using it (possibly) moves some of your business logic into your template, but sometimes that is OK.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜