Flask Webアプリケーションで‘HTMLテンプレートにアプリから文字列を表示するコードを紹介します。
こちらの記事では、FlaskアプリケーションでHTMLテンプレートを利用する方法を紹介しました。
この記事では、HTMLテンプレートにPythonのコードから出力するコードを紹介します。
HTMLテンプレートのFlaskアプリケーションを作成します。手順はこちらの記事を参照してください。
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>テンプレートへの出力のデモ</title>
</head>
<body>
<h1>テンプレートへの出力のデモ</h1>
<p>HTMLのテンプレートページです。</p>
<p>{{ out_content }}</p>
</body>
</html>
"""
This script runs the application using a development server.
It contains the definition of routes and views for the application.
"""
from flask import Flask, render_template
app = Flask(__name__)
# Make the WSGI interface available at the top level so wfastcgi can get it.
wsgi_app = app.wsgi_app
@app.route('/')
def hello():
"""Renders a sample page."""
mymessage = "アプリからのメッセージです。"
return render_template("index.html", out_content=mymessage)
if __name__ == '__main__':
import os
HOST = os.environ.get('SERVER_HOST', 'localhost')
try:
PORT = int(os.environ.get('SERVER_PORT', '5555'))
except ValueError:
PORT = 5555
app.run(HOST, PORT)
HTMLのテンプレートにアプリケーションから表示したい位置にプレースホルダーを作成します。
プレースホルダーの書式は以下です。
{{ [プレースホルダー名] }}
以下のコードでは、out_content
という名称のプレースホルダを配置しています。
<p>{{ out_content }}</p>
Webアプリケーションのルートにアクセスした際の処理のコードです。
return render_template()
によりレスポンスにHTMLのテンプレートを返す処理となっています。
render_template は以下の書式となっています。
render_template([HTMLテンプレートファイル], [プレースホルダー名]=[値])
以下のコードでは、out_content のプレースホルダーにmymessage変数の値を表示する動作になります。
@app.route('/')
def hello():
"""Renders a sample page."""
mymessage = "アプリからのメッセージです。"
return render_template("index.html", out_content=mymessage)
プロジェクトを実行します。
下図のページが表示されます。アプリケーションのコードに記述した内容がページに表示されました。
プレースホルダーが複数の場合の例です。
以下のHTMLテンプレートを作成します。3つのプレースホルダーを記述しています。
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<title>テンプレートへの出力のデモ</title>
</head>
<body>
<h1>テンプレートへの出力のデモ</h1>
<p>HTMLのテンプレートページです。</p>
<p>{{ out_content1 }}</p>
<p>{{ out_content2 }}</p>
<p>{{ out_content3 }}</p>
</body>
</html>
"""
This script runs the application using a development server.
It contains the definition of routes and views for the application.
"""
from flask import Flask, render_template
import datetime
app = Flask(__name__)
# Make the WSGI interface available at the top level so wfastcgi can get it.
wsgi_app = app.wsgi_app
@app.route('/')
def hello():
"""Renders a sample page."""
mymessage = "アプリからのメッセージです。"
return render_template("index.html", out_content=mymessage)
@app.route('/m')
def hello2():
now = datetime.datetime.now()
mymes1 = "アプリからのメッセージです。"
mymes2 = now.strftime('%Y-%m-%d %H:%M:%S')
mymes3 = "ありがとうございます。"
return render_template("index2.html", out_content1=mymes1, out_content2=mymes2, out_content3=mymes3)
if __name__ == '__main__':
import os
HOST = os.environ.get('SERVER_HOST', 'localhost')
try:
PORT = int(os.environ.get('SERVER_PORT', '5555'))
except ValueError:
PORT = 5555
app.run(HOST, PORT)
templates\index2.htmlのテンプレートには、3つのプレースホルダーを記述しています。
時刻を扱うため、datetimeモジュールをインポートしています。
import datetime
(アプリケーションルートURL)/m
のURLにアクセスしたときの処理を以下のコードで記述しています。
index2.htmlテンプレートを返します。プレースホルダーに出力する3つの文字列を準備します。
2つ目のmymes2変数には、現在の日時を文字列として代入しています。
render_template()関数は以下の書式です。
render_template([HTMLテンプレートファイル], [プレースホルダー名1]=[値1], [プレースホルダー名2]=[値2] ... [プレースホルダー名n]=[値n] )
@app.route('/m')
def hello2():
now = datetime.datetime.now()
mymes1 = "アプリからのメッセージです。"
mymes2 = now.strftime('%Y-%m-%d %H:%M:%S')
mymes3 = "ありがとうございます。"
return render_template("index2.html", out_content1=mymes1, out_content2=mymes2, out_content3=mymes3)
プロジェクトを実行し、(アプリケーションルートURL)/m
のURLにアクセスします。
下図のページが表示されます。3つのプレースホルダーに文字列が出力できています。2番目のプレースホルダーには
現在の日時も表示できています。
Flask Webアプリケーションで‘HTMLテンプレートにアプリから文字列を表示できました。