1
1

More than 1 year has passed since last update.

【Flask】url_forを使用して画像ファイルを表示する方法

Posted at

Flaskのurl_forを使用して画像を表示する方法を紹介します。

ディレクトリ構成

今回例として使用するディレクトリ構成は以下のようになってます。

flask$ tree .
.
├── __pycache__
│   └── func.cpython-310.pyc
├── main.py
├── static
│   ├── images
│   │   ├── default.png
│   │   ├── home.png
│   │   └── logo.png
│   ├── js
│   └── style
│       └── style.css
└── templates
    ├── index.html
    └── layout.html

9 directories, 18 files

static/images/default.pngファイルを表示するやり方を記載します。

static配下を使用するためには

今回、cssファイルやjsファイル、imageファイルはstaticディレクトリ配下に入れています。
こちらを使用するために、main.pyに以下を記載します。

main.py
app = Flask(__name__, static_folder="./static/")

これによりmain.pyを実行するとurl_forでstaticを指定した際に、
static配下を使用することができるようになります。

url_forを使用して画像ファイルを表示する方法

index.htmlは以下になります。

index.html
<ul>
  <li>
    <a href="{{ url_for('aaa')}}">
      <img src="{{ url_for('static', filename='/images/default.png')}}" alt="">
      <p>aaa</p>
    </a>
  </li>
  <li>
    <a href="{{ url_for('bbb')}}">
      <img src="{{ url_for('static', filename='/images/default.png')}}" alt="">
      <p>bbb</p>
    </a>
  </li>
  <li>
    <a href="{{ url_for('ccc')}}">
      <img src="{{ url_for('static', filename='/images/default.png')}}" alt="">
      <p>ccc</p>
    </a>
  </li>
</ul>

url_forを使用している以下部分になります。

<img src="{{ url_for('static', filename='/images/default.png')}}" alt="">

これによりstatic配下のimages/default.pngを表示することができます。

ちなみにこちらをChromeの検証ツールで覗いてみると以下のようになります

<img src="/static/images/default.png')}}" alt="">

純粋にHTMLで記述すると上記のようになります。

staticを指定することでcssやimageファイルがバラバラになることがないのが、
良い点かと思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1