render_template
が記述されているか確認してください。例外がスローされました
name 'render_template' is not defined
Flask Webアプリケーションで‘HTMLテンプレートを利用する手順を紹介します。
こちらの記事ではシンプルなFlaskアプリケーションの作成手順を紹介しました。
この記事では、FlaskアプリケーションでHTMLテンプレートを利用する手順を紹介します。
PythonのFlaskアプリケーションを作成します。詳細な手順はこちらの記事を参照してください。
プロジェクトの直下に[templates]フォルダを作成します。
templatesフォルダ内にテンプレートのHTMLファイルを作成します。今回は、index.html ファイルを作成しています。
テンプレートHTMLファイルとapp.pyを変更します。
以下のコードを記述します。
<!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>
</body>
</html>
app.pyは import にrender_template
を追記します。
また、return render_template("index.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."""
return render_template("index.html")
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)
インポート文です。Flaskとrender_template をインポートしています。
from flask import Flask, render_template
Webアプリケーションのルートにアクセスした際の処理を記述しています。
return render_template([HTMLテンプレートファイル])
の記述により、テンプレートをアクセスのレスポンスとして返しています。
@app.route('/')
def hello():
"""Renders a sample page."""
return render_template("index.html")
プロジェクトを実行します。Webブラウザが起動し、下図のページが表示されます。
テンプレートHTMLファイルの内容が表示できています。
render_template
が記述されているか確認してください。例外がスローされました
name 'render_template' is not defined
Flask WebアプリケーションでHTMLページテンプレートを利用できました。