Automatically add a variable into context on per-application basis in Django?
I want to add a context variable in Django, so that I could define its value on per-application basis, or leave it empty.
Example:
apps/someapp/views.py:
def_context_var('app_name', 'Calendar')
templates/base.html:
{% if app_name %}You are in {{ app_name }} app.{% endif %}
....
{% if app_name %}Subsections of {{ app_name }}: ...{% endif %}
I considered the following:
- Declare a variable in the app (in a view, or in URLs), and make a context processor. But I can't understang how to extract that var given the request object.
- Put decorators on views. Hm, I don't like the idea: too much boilerplate or duplicated code.
- #1 but nicer: make methods (like in the example above) that are executed on server restart, write the data into a dict, then a context开发者_StackOverflow中文版 processor somehow (how?) gets the application name and extracts the data from the dict. Where do I put the method, the dict, how does the context processor know where the view object is in?
You can call resolve(request.path)
in a context processor to resolve the current url. See the django documentation on resolve for its return values, especially app_name
.
精彩评论