Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> {% endfor %} 

At the moment, I need to pass nav_obj in every view. Is there any way to have this sent automatically?

like image 789
Hellnar Avatar asked Feb 08 '10 17:02

Hellnar


People also ask

How do I change the value of a variable in a 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.

What does {{ NAME }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

Does Django use Jinja2?

Jinja is officially supported by Django, and even before that there were third-party packages that allowed you to use it. The only real compatibility issue is that you can't use Django's custom template tags in a Jinja template.


2 Answers

Write your own context processor.

like image 193
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 06:09

Ignacio Vazquez-Abrams


Inclusion tags might be a good-looking alternative to a context processor.

like image 20
speakman Avatar answered Sep 22 '22 06:09

speakman