如何获取模板中当前应用的名称? [英] How to get the name of current app within a template?
问题描述
在模板代码中访问当前应用程序的名称最简单的方法是什么?
What's the simplest way to access the name of the current app within template code?
或者,定义模板变量的最简单的方法是保存当前的应用程序?
Alternatively, what's the simplest way to define a template variable to hold the name of the current app?
(这里的目的是尽量减少我重命名应用程序时需要编辑的地方数量。)
(The goal here is to minimize the number of places I need to edit if I rename an app.)
推荐答案
有一种获取当前请求的应用程序名称的方法。
首先,在项目的urls.py中,考虑您的应用程序被调用'main'
:
There's a way to obtain an app name for a current request.
First, in your project's urls.py, considering your app is called 'main'
:
#urls.py
url(r'^', include('main.urls', app_name="main")),
然后,一个上下文processsor:
Then, a context processsor:
#main/contexts.py
from django.core.urlresolvers import resolve
def appname(request):
return {'appname': resolve(request.path).app_name}
不要忘记在您的设置中启用它:
Don't forget to enable it in your settings:
#settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.request",
"main.contexts.appname",)
您可以像任何其他变量一样在模板中使用它: {{appname}}
。
You can use it in your template like any other variable: {{ appname }}
.
这篇关于如何获取模板中当前应用的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!