Defining “global variable” in Django templates

后端 未结 5 917
情书的邮戳
情书的邮戳 2020-12-16 04:52

I\'m doing something like:

{% extends \'base.html\' %}
{% url myapp.views.dashboard object as object_url %}
{% block sidebar %}
... {{ object_url }} ...
{% e         


        
5条回答
  •  渐次进展
    2020-12-16 05:46

    You could write a custom template tag:

    @register.simple_tag(takes_context=True)
    def set_global_context(context, key, value):
        """
        Sets a value to the global template context, so it can
        be accessible across blocks.
    
        Note that the block where the global context variable is set must appear
        before the other blocks using the variable IN THE BASE TEMPLATE.  The order
        of the blocks in the extending template is not important. 
    
        Usage::
            {% extends 'base.html' %}
    
            {% block first %}
                {% set_global_context 'foo' 'bar' %}
            {% endblock %}
    
            {% block second %}
                {{ foo }}
            {% endblock %}
        """
        context.dicts[0][key] = value
        return ''
    

提交回复
热议问题