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?
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.
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.
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.
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')}
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 ''
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With