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?
B701: Test for not auto escaping in jinja2When autoescaping is enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables. Without escaping HTML input the application becomes vulnerable to Cross Site Scripting (XSS) attacks. Unfortunately, autoescaping is False by default.
Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.
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.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With