Search code examples
pythonhtmlflaskjinja2

How do you create a Jinja list and collect a Jinja list in the flask app?


I can make a list and get it, but it only gives me one of those items in the list, if I try to get any others outside of the first index I get the list index out of range exception

The list I've tried to make (the only thing I've found online).

{% set infoList = [1,2] %}
<form method="post"><button name="add_to_collection" value={{infoList}}>{{collection[0]}}</button></form>

The way I've tried to collect the list

information = request.form.getlist('information')

When I try to get both indexes 0 & 1, I get List Out Of Index Range, I can only get the first. If I print out that list, this is the output

[1,

not sure how this works and couldn't find it online anywhere.


Solution

  • The problem is that you need to escape the comma. If you inspect the button you'll see this:

    <button name="add_to_collection" value="[1," 2]="">text here</button>
    

    Here, it thinks you're adding two things to the html. I'm honestly not sure if you can set an input value as a list.

    Try this:

    {% set infoList = "[1,2]" %}
    

    or this:

    <button name="add_to_collection" value="{{ infoList }}">{{collection[0]}}</button>
    

    or even this if the list never changes:

    <button name="add_to_collection" value="[1,2]">{{collection[0]}}</button>
    

    and then deal with turning it back into a list when you're in the backend.