开发者

Automatically add a variable into context on per-application basis in Django?

开发者 https://www.devze.com 2023-01-20 15:10 出处:网络
I want to add a context variable in Django, so that I could define its value on per-application basis, or leave it empty.

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:

  1. 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.
  2. Put decorators on views. Hm, I don't like the idea: too much boilerplate or duplicated code.
  3. #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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号