Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining "global variable" in Django templates

I'm doing something like:

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

Django documentation says url templatetag can define a variable in context, but I don't get any value for object_url in the following blocks.

If I put the url templatetag at the beginning of each block, it works, but I don't want to "repeat myself".

Anyone knows a better solution?

like image 622
Achimnol Avatar asked Jun 23 '09 01:06

Achimnol


People also ask

How do you define a variable in a template?

In the template, you use the hash symbol, # , to declare a template variable. The following template variable, #phone , declares a phone variable with the <input> element as its value.

Can we create a variable in Django template?

We can set the value of a variable in the Django template using with tag. This will output the below content. One downside of this approach is that we have to write the lines where we are accessing the variable inside with and endwith block. Using with is useful when using a costly variable multiple times.

Can I use filter () in Django template?

Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can't modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one's own need.


2 Answers

If the URL is view specific, you could pass the URL from your view. If the URL needs to be truly global in your templates, you could put it in a context processor:

def object_url(request):
    return {'object_url': reverse('myapp.views.dashboard')}
like image 60
defrex Avatar answered Sep 18 '22 18:09

defrex


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 ''
like image 21
seddonym Avatar answered Sep 19 '22 18:09

seddonym