在Django模板中定义"全局变量"

Ach*_*nol 6 django django-templates

我做的事情如下:

{% extends 'base.html' %}
{% url myapp.views.dashboard object as object_url %}
{% block sidebar %}
... {{ object_url }} ...
{% endblock %}
{% block content %}
... {{ object_url }} ...
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

Django文档说url templatetag可以在上下文中定义变量,但是我object_url在以下块中没有得到任何值.

如果我将url templatetag放在每个块的开头,它可以工作,但我不想"重复自己".

谁知道更好的解决方案?

def*_*rex 7

如果URL是特定于视图的,则可以从视图中传递URL.如果URL需要在模板中真正全局化,则可以将其放在上下文处理器中:

def object_url(request):
    return {'object_url': reverse('myapp.views.dashboard')}
Run Code Online (Sandbox Code Playgroud)

  • 即使它没有在每个模板中使用它也不会伤害任何东西将它放入上下文处理器......除非它当然正在进行数据库查找,在这种情况下它会影响网站性能. (3认同)

sed*_*nym 5

您可以编写自定义模板标签:

@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 ''
Run Code Online (Sandbox Code Playgroud)