How do I get a list of all the arguments passed to a Jinja2 template?
If I have an extremely generic template and I want to list all the arguments passed (for debug reasons) is there a way to do it?
Something like:
mytemplate.html
{% for argument in LIST_OF_ARGUMENT %}
{{ argument }}<br>
{% endfor %}
so in the view /foobar
if I call the template in this way:
return render_template('mytemplate.html', form=myform, foo='bar')
I get
the_content_of_form <br>
bar <br>
while if I call the template in this way:
return render_template('mytemplate.html', lorem=ipsum, fooooo='barrrrr')
I get
the_content_of_lorem <br>
barrrrr <br>
Variables. Template variables are defined by the context dictionary passed to the template. You can mess around with the variables in templates provided they are passed in by the application. Variables may have attributes or elements on them you can access too.
When 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.
Well you just need to pass them as an argument to render_template, probably the most common use of this involves passing a list of dictionaries as an argument to render template:
def Viewfunction():
#do something, get something from db as result and then
arguments = [dict(name=row[0],age=row[1]) for row in result.fetchall()]
return render_template('mytemplate.html', form=myform, arguments=arguments)
and then access them like so:
{% for item in arguments %}
{{ item.name }}
{{ item.age }}
{% endfor %}
Obviously you can also pass all other lists, not just lists of dictionaries to the template, you loop over them in a very similar way.
As for debugging I have found Flask built in debugging tools very useful, if you get an exception you just get a page where you can execute code, if you're interested in all your variables there you can simply type locals() into one of the frames within stacktrace. You just need to enable debug mode to make use of it, just remember to turn it off in production.
Here's a working example for you, it's taken from flaskr sample app included in flask when you download it under examples folder:
@app.route('/')
def show_entries():
db = get_db()
cur = db.execute('select title, text from entries order by id desc')
entries = cur.fetchall()
return render_template('show_entries.html', entries=entries,local=locals())
When you do:
{% for item in local %}
{{ item }}
{% endfor %}
you'll get db cur entries, is this what you want?
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