How to create an item list to use multiple times on a Jinja2 template page?

1.8k Views Asked by At

I want to create an HTML option list and display it multiple times on the template page. I tried to iterate through the list passed on to the template but this seems only to work once on the page:

{% for item in points %}
<option value="{{ item }}">{{ item }}</option>
{% else %}
No item found..
{% endfor %}

The second time I iterate, I get the exception "No item found..". I could not figure out how to create this list once and re-use it with Jinja.

What am I doing wrong? Is there a better solution?

The template file:

{% extends "layout.html" %}
{% block body %}
{% if session.username %}
    <p>Welcome {{ session.username }}!</p>

    <p>Connect Points:</p>
    <form action="{{ url_for('add_con') }}" method=post>
        First Point<br>
        <input list="first_point" name="first_point">
            <datalist id="first_point">
                {% for item in points %}
                <option value="{{ item }}">{{ item }}</option>
                {% else %}
                <option><b>No Item found..</b></option>
                {% endfor %}
            </datalist>
            <br />Name:<br />
            <input type="text" name="name">
            Second Point<br>
            <input list="second_point" name="second_point">
            <datalist id="second_point">
                {% for item in points %}
                    <option value="{{ item }}">{{ item }}</option>
                {% else %}
                    <option><b>No Item found..</b></option>
                {% endfor %}
            </datalist>
        <input type="submit" value="Add Point">
    </form>
{% else %}
<p>You are not logged in!</p>
{% endif %}
{% endblock %}
1

There are 1 best solutions below

0
On BEST ANSWER

As pointed out by Peter Wood in the comments, points is a generator:

You need to turn it into a list: list(graph.find())

Thanks!