用烧瓶和jinja迭代目录

时间:2016-09-19 04:32:05

标签: python-2.7 flask jinja2

我的目标是遍历静态文件中的目录并显示除“动态”之外的所有图片。我有迭代工作,我只是不能让忍者方面的工作来显示我的照片。

server.py

@app.route('/ninja')
def ninja():
    for filename in os.listdir('static/images'):
        if filename.endswith(".jpg") and filename != "notapril.jpg":
            allninjas = (os.path.join('static/images', filename))
        else:
            continue
    return render_template('ninja.html', color=allninjas)

ninja.html:

<body>

    {% for item in navigation %}
        <img src="{{ allninjas }}"/>
    {% endfor %}


    {% for filename in listdir %}
    {% if filename %}
        <img src="{{ allninjas }}"/>
    {% endif %}
    {% endfor %}


    <img src="{{ color }}"/>

</body>

底部标签将显示我目录中最后一只忍者龟的图片。我不能得到其他忍者和if循环工作。 请帮助我本周开始忍者。

1 个答案:

答案 0 :(得分:1)

这里有几件事情。让我们从您的Python代码开始。您需要创建一个列表,如@davidism所述,然后将该列表传递给您的模板。像这样......

@app.route('/ninja')
def ninja():
    allninjas = []
    for filename in os.listdir('static/images'):
        if filename.endswith(".jpg") and filename != "notapril.jpg":
            allninjas.append(os.path.join('static/images', filename))
        else:
            continue
    return render_template('ninja.html', color=allninjas)

现在,您的模板已将某些内容分配给其color变量,该变量在Python代码中名为allninjas。这也是你的循环无法正常工作的原因,因为你没有为这些变量分配任何内容,只有color

您可能要做的是将您的通话更改为render_template,如下所示:

return render_template('ninja.html', allninjas=allninjas)

然后将模板更改为:

<body>

{% for filename in allninjas %}
    {% if filename %} # not sure you really need this line either
        <img src="{{ filename }}"/>
    {% endif %}
{% endfor %}

</body>

我删除了很多。我不确定你和其他部分做了什么,但我会告诉你为什么我把它们拿走了。首先,你有两个循环打印img标签,图像源设置为allninjas,它只打印每个图像中的两个,除了你的循环变量在每种情况下都是未定义的。 navigationlistdir不会从您的Python代码发送到模板,因此模板不知道它们是什么,并且无法循环它们。

您的代码定义了color,但没有其他内容,因此可以显示一个图像。我不确定你真正想要的所有其他变量是什么,所以除非你进一步解释,否则我无法帮助你。

如果要定义所有这些变量,模板调用将如下所示:

return render_template('ninja.html', navigation=navigation, 
                                     listdir=listdir, 
                                     allninjas=allninjas,
                                     color=color)

在每种情况下,例如color=color,第一部分color=指的是模板中的变量。您告诉模板应该为该变量分配什么。第二部分,在本例中为color,是您要发送到模板的Python代码中的变量。所以:

return render_template('templatename.html', template_variable=Python_variable)

我希望有所帮助。