Flask循环浏览静态目录中的图像

2024-05-23 14:33:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我建立了一个烧瓶网站:

.flask
   .static
      .images
      .css
   .templates

我有我的基本.py文件格式:

^{pr2}$

在公文包.html文件,我希望能够收集图像目录中的所有文件,并将它们显示为可单击的url。在

<section class="row">
  {% for image in path_to_folder %}
    <section class="col-md-4 col-sm-6" style="background-color: green;">
      {{ image }}
    </section>
  {% endfor %}
</section>

有没有一种简单的方法可以从images目录中获取所有的图像?我是否可以将图像存储到数组中,并将它们作为参数传递到render_模板('公文包.html“,图像=?”?在


Tags: 文件图像image目录flask烧瓶网站html
1条回答
网友
1楼 · 发布于 2024-05-23 14:33:39

您只需使用os.listdir来获取所有文件。在

@app.route('/portfolio')
def portfolio():
    images = os.listdir(os.path.join(app.static_folder, "images"))
    return render_template('portfolio.html', images=images)

然后在模板中:

^{pr2}$

相关问题 更多 >