簡體   English   中英

燒瓶循環遍歷靜態目錄中的圖像

[英]Flask loop through images in static directory

我有一個這樣的燒瓶網站:

.flask
   .static
      .images
      .css
   .templates

我的basic.py文件為:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/portfolio')
def portfolio():
    return render_template('portfolio.html')

if __name__ == '__main__':
    app.run(debug=True)

在Portfolio.html文件中,我希望能夠收集images目錄中的所有文件並將它們顯示為可單擊的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_template('portfolio.html',images =?“)嗎?

您可以簡單地使用os.listdir獲取所有文件。

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

然后在您的模板中:

<section class="row">
  {% for image in images %}
    <section class="col-md-4 col-sm-6" style="background-color: green;">
      <a href="{{ url_for('static', filename='images/' + image) }}">{{ image }}</a>
    </section>
  {% endfor %}
</section>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM