Skip to main content
 首页 » 编程设计

python之如何创建项目列表以在 Jinja2 模板页面上多次使用

2024年10月24日14yxwkf

我想创建一个 HTML 选项列表并在模板页面上多次显示它。我试图遍历传递给模板的列表,但这似乎只在页面上起作用一次:

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

我第二次迭代时,出现异常 “No item found..”。我不知道如何一次性创建此列表并在 Jinja 中重复使用它。

我做错了什么?有更好的解决方案吗?

模板文件:

{% 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 %} 

请您参考如下方法:

正如 Peter Wood 在评论中指出的那样,points 是一个生成器:

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

谢谢!