Flaskのrender_templateの使い方解説
2024年12月3日

こんにちは!
今回の記事では、Flaskのrender_templateの使い方について解説します。
render_templateとは、Flaskの標準的な関数で、HTMLテンプレートファイルを動的に生成し、ユーザーに返す役割を担っています。
簡単なWebページから、複雑なアプリケーションまで、どのようなアプリを作成するにしてもrender_templateを使うことになるでしょう。
そこで、今回はrender_templateのさまざまな使い方について詳しく解説します。
render_templateの基本的な使い方
まずは、render_templateの基本的な使い方について解説します。
Flaskのインストール
初めにFlaskの準備をします。以下のコマンドを実行して、Flaskをインストールしましょう。
pip install flask
Flaskのインストール方法についてはこちらの記事で詳しく解説しています。
【関連】Flaskのインストール方法とは?Flaskを使ってみよう
今回のディレクトリ構造
今回は簡単なflaskのアプリを作成して、render_templateの使い方を解説します。
以下のような構造のアプリを作成します。
flask_app/
│
├── app.py # Flaskアプリのメインファイル
├── templates/ # HTMLテンプレートを格納するディレクトリ
│ ├── index.html # ホームページのテンプレート
│ └── about.html # 他のページのテンプレート
Flaskのメインファイルである、app.pyとtemplatesディレクトリにHTMLテンプレートを作成します。
app.pyへrender_templateの記述
続いて、app.pyへrender_templateの記述をします。以下のように記述します。
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
上記では、Webページの/へアクセスすると、templatesディレクトリのindex.htmlを返すようになります。
templates/index.htmlを以下のように記述します。
<h1>Hello World!</h1>
続いて、Pythonを起動します。
python app.py
Webブラウザから、http://127.0.0.1:5000/へアクセスすると、index.htmlに記述した「Hello World!」が表示されます。
このように、render_templateはどのテンプレートファイルをユーザーに返すのかを指定します。
【関連】Jinja2とは何か?Pythonのテンプレートエンジンについて解説
render_templateの書式
render_templateは以下のように記述します。
render_template('[テンプレートファイル]', key1=value1, key2=value2)
テンプレートファイルの部分は、templatesディレクトリに格納されているテンプレートファイル名を記述します。
次に、キーワード引数を指定します。HTMLテンプレートに渡す変数を [キー] = [値]の形式で指定します。
具体例
例えば、以下のように、 [キー] = [値]を指定して、テンプレートで使用することができます。
@app.route('/')
def hello():
return render_template('hello.html', name="Alice", age=30)
テンプレート側では、{{ }}を使って、渡された変数を表示します。
<!DOCTYPE html>
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<p>You are {{ age }} years old.</p>
</body>
</html>
動的な値を渡す
動的な値を渡すことも可能です。
以下のように、usernameが変わる場合に便利です。以下では、値の部分に変数のusernameを指定しています。
@app.route('/user/<username>')
def user_profile(username):
return render_template('profile.html', username=username)
テンプレート側では、以下のように指定します。
<h1>Welcome, {{ username }}!</h1>
http://localhost:5000/user/John にアクセスすると以下のように表示されます。
Welcome, John!
テンプレートディレクトリを変更する場合
render_templateはデフォルトで、templatesディレクトリ配下にあるテンプレートファイルを指定します。
もし、templatesディレクトリ以外に保存する場合は、以下のように設定します。
app = Flask(__name__, template_folder='my_templates')
上記のように、Flaskオブジェクトを作成する際にtemplate_folderを指定します。
まとめ
Flaskのrender_templateは、HTMLテンプレートを動的に生成してWebアプリケーションを構築する上で欠かせない機能です。
本記事では、基本的な使い方から、動的な値の渡し方、テンプレートディレクトリの変更方法まで幅広く解説しました。
これを理解することで、ユーザーごとに異なるコンテンツを提供する柔軟なWebアプリケーションを作成できるようになります。特に、テンプレートエンジンJinja2と連携して変数やロジックをテンプレート内で活用することで、コードの再利用性が向上し、開発効率を高めることが可能です。
Flaskのシンプルさを活かしつつ、render_templateを効果的に活用して、より魅力的なWebアプリケーションを構築してください。
ここまでお読みいただきありがとうございました!
Pythonの基礎から応用まで学べる
Python WebAcademy
Python WebAcademyでは、Pythonの基礎からアーキテクチャなどの応用的な内容まで幅広く学べます。また、ブラウザ上で直接Pythonコードを試すことができ、実践的なスキルを身につけることが可能です。

インフラの学習はInfraAcademy

おすすめの記事









