【问题标题】:How to create an item list to use multiple times on a Jinja2 template page?如何在 Jinja2 模板页面上创建项目列表以多次使用?
【发布时间】:2015-06-18 12:53:19
【问题描述】:

我想创建一个 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 %}

【问题讨论】:

  • 你能告诉我们两个循环的页面吗?
  • points 是列表还是生成器?如果生成器用完,第二次它就不会做任何事情。
  • @PeterWood 它应该是一个发电机。我使用了py2neo的graph.find()link来返回保存在points中的节点列表。
  • 你需要把它变成一个列表:list(graph.find())

标签: python python-3.x for-loop flask jinja2


【解决方案1】:

正如 Peter Wood 在 cmets 中指出的,points 是一个生成器:

你需要把它变成一个列表:list(graph.find())

谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多