如何从 Jinja 2 模板中获取当前变量列表? [英] How to get a list of current variables from Jinja 2 template?

查看:25
本文介绍了如何从 Jinja 2 模板中获取当前变量列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我像这样返回 Jinja2 模板:return render_response('home.htm', **context)

然后如何从模板中获取上下文中的变量列表?

解决方案

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

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

  2. 使该函数在全局命名空间中可用;即 jinja2.Environment 或 jinja2.Template 全局字典

  3. 可选地,从上下文中过滤对象;例如,使用 callable() 跳过 Jinja 的默认全局辅助函数(range、joiner 等).这可以在上下文函数或模板中完成;在最有意义的地方.

示例:

<预><代码>>>>进口jinja2>>>>>>@jinja2.contextfunction... def get_context(c):...返回 c...>>>tmpl = """... {% for key, value in context().items() %}... {% 如果不可调用(值)%}... {{ 核心价值 }}... {% 万一 %}... {% endfor %}……">>>>>>模板 = jinja2.Template(tmpl)>>>template.globals['context'] = get_context>>>template.globals['callable'] = callable>>>>>>上下文 = {'a':1,'b':2,'c':3}>>>>>>打印(模板.渲染(**上下文))一:1c:3乙:2

[或者,使用 ('home.htm', context=context) 调用 render_response 以使其他解决方案起作用.]

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.

  1. Define a Jinja context function to return the jinja2.Context object, which is essentially a dictionary of the global variables/functions

  2. Make that function available in the global namespace; i.e. a jinja2.Environment or jinja2.Template globals dictionary

  3. 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.

Example:

>>> 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

[Alternately, call render_response with ('home.htm', context=context) to make the other solution work.]

这篇关于如何从 Jinja 2 模板中获取当前变量列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆