如何从Jinja 2模板获取当前变量的列表? [英] How to get a list of current variables from Jinja 2 template?
问题描述
如果我这样返回Jinja2模板:
return render_response('home.htm', **context)
If I return a Jinja2 template like so:
return render_response('home.htm', **context)
然后如何从模板中获取上下文中的变量列表?
How do then get a list of the variables in context from within the template?
推荐答案
从技术上讲,由于上下文不是作为命名字典传递的,因此需要做一些工作才能从模板内部生成上下文变量的列表.有可能.
Technically, because context is not passed as a named dictionary, a little work is required to generate a list of the context variables from inside a template. It is possible though.
-
定义 Jinja上下文函数返回jinja2.Context对象,该对象本质上是全局变量/函数的字典
Define a Jinja context function to return the jinja2.Context object, which is essentially a dictionary of the global variables/functions
使该功能在全局名称空间中可用;即jinja2.Environment或jinja2.Template全局字典
Make that function available in the global namespace; i.e. a jinja2.Environment or jinja2.Template globals dictionary
(可选)从上下文中过滤对象;例如,使用callable()
跳过Jinja的默认全局帮助器功能(范围,连接器等).这可以在上下文函数或模板中完成;最有意义的地方.
Optionally, filter objects from the context; for instance, use callable()
to skip Jinja's default global helper functions (range, joiner, etc.). This may be done in the context function or the template; wherever it makes the most sense.
示例:
>>> import jinja2
>>>
>>> @jinja2.contextfunction
... def get_context(c):
... return c
...
>>> tmpl = """
... {% for key, value in context().items() %}
... {% if not callable(value) %}
... {{ key }}:{{ value }}
... {% endif %}
... {% endfor %}
... """
>>>
>>> template = jinja2.Template(tmpl)
>>> template.globals['context'] = get_context
>>> template.globals['callable'] = callable
>>>
>>> context = {'a': 1, 'b': 2, 'c': 3}
>>>
>>> print(template.render(**context))
a:1
c:3
b:2
[或者,用('home.htm', context=context)
调用render_response
以使其他解决方案起作用.]
[Alternately, call render_response
with ('home.htm', context=context)
to make the other solution work.]
这篇关于如何从Jinja 2模板获取当前变量的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!