Django, global template variables

隐身守侯 提交于 2019-12-21 03:20:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!