假设我有一个具有以下上下文的 django 模板:
data1 = "this is data1"
data2 = "this is data2"
data_name = "data2"
现在我知道了data_name
(假设它是"data2"
),是否可以用它来访问变量data2
?
为了让我的意图更清楚,这就是你可以使用 Python 实现的方式
>>> a = 1
>>> b = 2
>>> name = 'a'
>>> locals()[name]
1
>>> name = 'b'
>>> locals()[name]
2
With 内置模板过滤器、标签 https://docs.djangoproject.com/en/1.6/ref/templates/builtins/, 不可能。你应该定义自定义标签 https://docs.djangoproject.com/en/1.6/howto/custom-template-tags/去做吧。
Example:
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def get_by_name(context, name):
return context[name]
用法示例(假设标签定义在APP_DIR/templatetags/name.py
):
>>> from django.template import Template, Context
>>> t = Template('''
... {% load name %} {# Don't forget to load #}
... {% get_by_name data_name %}
... ''')
>>> output = t.render(Context({
... 'data1': 'this is data1',
... 'data2': 'this is data2',
... 'data_name': 'data2',
... }))
>>> print(output)
this is data2
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)