Creating 2 dimensional array in Python Flask application Jinja2 Template

3.3k Views Asked by At

Within my Flask index.html template I wish to create a 2 dimensional array within a for loop. The for loop works perfectly fine but trying to 'set' an array that's multidimensional is not working. For example, one of the many things I've tried is:

{% set matrix = [[] for x in range(sizeOfSomething)] %}

I get the following exception:

jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'for'

Any suggestions?

1

There are 1 best solutions below

1
On BEST ANSWER

Jinja2 won't allow list comprehensions so this won't work.

The best approach is to take whatever you are doing in the loops and move it into app.py and pass the matrix to the template as a variable. You may find custom filters to be useful in processing the matrix within the template.