Django, global template variables
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>
{% 开发者_C百科endfor %}
At the moment, I need to pass nav_obj in every view. Is there any way to have this sent automatically?
Write your own context processor.
Inclusion tags might be a good-looking alternative to a context processor.
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 %}
As the accepted answers already says, use context processors. Here's how to make them work with the current Django version:
First, create a function which accepts a request and returns a dictionary with your global template variables:
def load_nav_obj(request):
nav_obj = NavigationObject.objects.all()
return {'nav_obj': nav_obj}
A good place for this function would be in a file context_processors.py
in your main app.
Now, tell your app to use this context processor for all rendered templates. In your settings.py
, add myapp.context_processors.load_nav_obj
in the TEMPLATE
settings:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# Insert your context processors here
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
...
'myapp.context_processors.load_nav_obj',
],
},
},
]
That's it! You can now use the variable {{nav_obj}}
in all templates!
You can also look at Django-navbar for it's documentation and tests..
精彩评论