我有一些东西在设置。py,我想能够从模板访问,但我不知道如何做到这一点。我已经试过了
{{CONSTANT_NAME}}
但这似乎并不奏效。这可能吗?
我有一些东西在设置。py,我想能够从模板访问,但我不知道如何做到这一点。我已经试过了
{{CONSTANT_NAME}}
但这似乎并不奏效。这可能吗?
当前回答
我稍微改进了chrisdew的答案(创建自己的标签)。
首先,创建文件yourapp/templatetags/value_from_settings.py,在其中定义你自己的新标签value_from_settings:
from django.template import TemplateSyntaxError, Variable, Node, Variable, Library
from yourapp import settings
register = Library()
# I found some tricks in URLNode and url from defaulttags.py:
# https://code.djangoproject.com/browser/django/trunk/django/template/defaulttags.py
@register.tag
def value_from_settings(parser, token):
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError("'%s' takes at least one " \
"argument (settings constant to retrieve)" % bits[0])
settingsvar = bits[1]
settingsvar = settingsvar[1:-1] if settingsvar[0] == '"' else settingsvar
asvar = None
bits = bits[2:]
if len(bits) >= 2 and bits[-2] == 'as':
asvar = bits[-1]
bits = bits[:-2]
if len(bits):
raise TemplateSyntaxError("'value_from_settings' didn't recognise " \
"the arguments '%s'" % ", ".join(bits))
return ValueFromSettings(settingsvar, asvar)
class ValueFromSettings(Node):
def __init__(self, settingsvar, asvar):
self.arg = Variable(settingsvar)
self.asvar = asvar
def render(self, context):
ret_val = getattr(settings,str(self.arg))
if self.asvar:
context[self.asvar] = ret_val
return ''
else:
return ret_val
你可以通过以下方式在模板中使用这个标签:
{% load value_from_settings %}
[...]
{% value_from_settings "FQDN" %}
或通过
{% load value_from_settings %}
[...]
{% value_from_settings "FQDN" as my_fqdn %}
as的优点是…这使得它很容易通过一个简单的{{my_fqdn}}在blocktrans块中使用。
其他回答
我发现最简单的方法是一个自定义模板标签:
from django import template
from django.conf import settings
register = template.Library()
# settings value
@register.simple_tag
def settings_value(name):
return getattr(settings, name, "")
用法:
{% settings_value "LANGUAGE_CODE" %}
Django提供了对模板中某些常用的设置常量的访问,比如settings。MEDIA_URL和一些语言设置,如果你使用django内置的通用视图或在render_to_response快捷函数中传入context实例关键字参数。以下是每种情况的示例:
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic.simple import direct_to_template
def my_generic_view(request, template='my_template.html'):
return direct_to_template(request, template)
def more_custom_view(request, template='my_template.html'):
return render_to_response(template, {}, context_instance=RequestContext(request))
这些视图都有一些常用的设置,比如settings。模板可用的MEDIA_URL为{{MEDIA_URL}},等等。
如果你在设置中寻找对其他常量的访问,那么只需将你想要的常量解包,并将它们添加到你在视图函数中使用的上下文字典中,如下所示:
from django.conf import settings
from django.shortcuts import render_to_response
def my_view_function(request, template='my_template.html'):
context = {'favorite_color': settings.FAVORITE_COLOR}
return render_to_response(template, context)
现在你可以访问设置了。在模板中使用{{FAVORITE_COLOR}}。
查看django-settings-export(免责声明:我是这个项目的作者)。
例如……
$ pip install django-settings-export
settings.py
TEMPLATES = [
{
'OPTIONS': {
'context_processors': [
'django_settings_export.settings_export',
],
},
},
]
MY_CHEESE = 'Camembert';
SETTINGS_EXPORT = [
'MY_CHEESE',
]
template.html
<script>var MY_CHEESE = '{{ settings.MY_CHEESE }}';</script>
对于那些想要使用@Berislav的方法(自定义模板标签)和if标签的人:
/ app / templatetags / my_settings.py:
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def settings_value(name):
return getattr(settings, name, "")
模板文件:
<!-- Load your tags -->
{% load my_settings %}
{% settings_value 'ENABLE_FEATURE_A' as ENABLE_FEATURE_A %}
{% if ENABLE_FEATURE_A %}
<!-- Feature A stuffs -->
{% endif %}
我喜欢Berislav的解决方案,因为在简单的网站上,它干净有效。我不喜欢的是随意地暴露所有的设置常数。所以我最后是这样做的:
from django import template
from django.conf import settings
register = template.Library()
ALLOWABLE_VALUES = ("CONSTANT_NAME_1", "CONSTANT_NAME_2",)
# settings value
@register.simple_tag
def settings_value(name):
if name in ALLOWABLE_VALUES:
return getattr(settings, name, '')
return ''
用法:
{% settings_value "CONSTANT_NAME_1" %}
This protects any constants that you have not named from use in the template, and if you wanted to get really fancy, you could set a tuple in the settings, and create more than one template tag for different pages, apps or areas, and simply combine a local tuple with the settings tuple as needed, then do the list comprehension to see if the value is acceptable. I agree, on a complex site, this is a bit simplistic, but there are values that would be nice to have universally in templates, and this seems to work nicely. Thanks to Berislav for the original idea!