Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

jinja2 - How to get a list of current variables from Jinja 2 template?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...