且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Jinja 2模板获取当前变量的列表?

更新时间:2023-11-02 17:00:04

从技术上讲,由于上下文不是作为命名字典传递的,因此需要做一些工作才能从模板内部生成上下文变量的列表.有可能.

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.

  1. 定义 Jinja上下文函数返回jinja2.Context对象,该对象本质上是全局变量/函数的字典

  1. 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.]