问题
I have a base template file (base.html) and every other template extends to it and generates content using its blocks. Certain variables, such as nav_obj, are used in the base template file.
View:
nav_obj = NavigationObject.objects.all()
Base template:
{% for object in nav_obj %}
<a href="{{ object.link }}">{{ object.title }}</a>
{% endfor %}
At the moment, I need to pass nav_obj in every view. Is there any way to have this sent automatically?
回答1:
Write your own context processor.
回答2:
Inclusion tags might be a good-looking alternative to a context processor.
回答3:
There is an alternative, redirect here: Defining "global variable" in Django templates
Snippet example usage:
{% setglobal foo 0 %}
value={% getglobal foo %}
{% incrementglobal foo 0 %}
value={% setglobal foo %}
回答4:
You can also look at Django-navbar for it's documentation and tests..
来源:https://stackoverflow.com/questions/2223429/django-global-template-variables