代码之家  ›  专栏  ›  技术社区  ›  culebrón

在Django中根据每个应用程序自动将变量添加到上下文中?

  •  2
  • culebrón  · 技术社区  · 14 年前

    我想在Django中添加一个上下文变量,以便可以根据每个应用程序定义它的值,或者将其保留为空。

    apps/someapp/views.py:

    def_context_var('app_name', 'Calendar')
    

    模板/base.html:

    {% if app_name %}You are in {{ app_name }} app.{% endif %}
    ....
    {% if app_name %}Subsections of {{ app_name }}: ...{% endif %}
    

    我考虑了以下几点:

    1. 在应用程序(视图或url)中声明一个变量,并生成一个上下文处理器。但我无法理解如何在给定请求对象的情况下提取该变量。
    2. 让装饰师看风景。嗯,我不喜欢这个主意:太多的样板文件或重复的代码。
    1 回复  |  直到 14 年前
        1
  •  2
  •   Bernhard Vallant    14 年前

    你可以打电话 resolve(request.path) django documentation on resolve for its return values ,尤其是 app_name