简体   繁体   中英

Jinja2 template: how to add extra check in for loop that we're not iterating over a string?

At my company we have "non-computer people" that use jinja2 to create templates of documents, with data coming from various sources (then some python scripts combine the data and the templates in order to generate pdf/docx etc.)

One extremely common problem we face is the following:

We have input data that looks like this:

NAME: "something"
NAMES: ["robert", "edouard", "jeanne"]
AGES: [25, 36, 28]

(ie a lot of arrays of the same size because there's the implicit contract that they are actually linked together)

and the template

{% for name in NAME %}
   Hello {{ name }}, you are {{ AGES[loop0.index0] }}

{% endfor %}

and as you can see here, a one letter mistake and you have a IndexError, as here you are iterating on the string NAME instead of the list NAMES , and when the template is very long and the number of variables high, it can become very tedious to debug and find the source of the error.

And it's 90% of the errors we have with people writing templates.

So is there a way for us in the python jinja library to override for blocks in order to add an additional check that the variable is a list (we don't manipulate any other kind of iterable) ?

We could create an extension that adds "forlist" blocks, but we would need to recode all the loop.index0 etc. logic that we use a lot (or am i mistaken) ? Additionally, as this extension would not be the default, the chance people adopt it is very low, and we will not avoid someone in the wild continuing to use for blocks.

Check this post: Testing for a List in Jinja2 From reading your post I found that applaying a custom filter might be the way to do it. Pardon my social skills are not super.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM