How to get a list of arguments in a Jinja2 template

How to get a list of all arguments passed to a Jinja2 template?

If I have a very general template and want to list all the arguments passed (for debugging reasons), is there a way to do this?

Sort of:

mytemplate.html {% for argument in LIST_OF_ARGUMENT %} {{ argument }}<br> {% endfor %} 

therefore in the view /foobar

if I call the template this way:

 return render_template('mytemplate.html', form=myform, foo='bar') 

I get

 the_content_of_form <br> bar <br> 

if I call the template this way:

 return render_template('mytemplate.html', lorem=ipsum, fooooo='barrrrr') 

I get

 the_content_of_lorem <br> barrrrr <br> 
+4
source share
2 answers

Well, you just need to pass them as an argument to render_template, perhaps the most common use of this involves passing a list of dictionaries as an argument to render the 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 as follows:

  {% for item in arguments %} {{ item.name }} {{ item.age }} {% endfor %} 

Obviously, you can also transfer all other lists, and not just lists of dictionaries into a template, you alternate them with them very similarly.

Regarding debugging, I found that Flask built into debugging tools is very useful, if you get an exception, you just get a page where you can execute code, if you are interested in all your variables, you can just type locals () into one from frames inside stacktrace. You just need to enable debugging mode to use it, just remember to turn it off during production.

Here's a working example, taken from the flaskr sample application included in the flask when you load it into the 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 get db cur entries, is that what you want?

+1
source

Take a look at jinja2.runtime.Context

"The template context contains the template variables. It stores the values ​​passed to the template, as well as the names that the template exports:

"The template context supports read-only title operations (get, keys, values, items, iterkeys, itervalues, iteritems, getitem , contains ). Resolve (), which does not fail with KeyError, but returns an Undefined object for missing variables."

0
source

Source: https://habr.com/ru/post/1495363/


All Articles