更新时间:2023-11-02 17:18:04
从技术上讲,因为上下文不是作为命名字典传递的,所以需要做一些工作才能从模板内部生成上下文变量列表.不过有可能.
定义一个 Jinja 上下文函数返回 jinja2.Context 对象,它本质上是一个全局变量/函数的字典
使该函数在全局命名空间中可用;即 jinja2.Environment 或 jinja2.Template 全局字典
可选地,从上下文中过滤对象;例如,使用 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.
Define a Jinja context function to return the jinja2.Context object, which is essentially a dictionary of the global variables/functions
Make that function available in the global namespace; i.e. a jinja2.Environment or jinja2.Template globals dictionary
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.]