English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Flask テンプレート

Flaskは、特定のURLにバインドされた関数の出力をHTML形式で返すことができます。以下のスクリプトでは、hello()関数は追加の<hタグを使用して表示されます。1>タグで表示 ‘Hello World’

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ja.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask
 app = Flask(__name__)
 @app.route('/')
 def index():
     return '<html><body><h1‘Hello World’</h1></body></html>'
 if __name__ == '__main__':
     app.run(debug=True)

しかし、PythonコードからHTMLコンテンツを生成することは非常に厄介です。特に可変データやPython言語の要素(条件やループ)を配置する必要がある場合にその通りです。HTMLコードをエスケープする必要があります。

Jinjaを利用2テンプレートエンジンテクノロジーを使用して、関数からハードコードされたHTMLを返す必要はありません。以下のコードのように、render_template()関数を使用してHTMLファイルをレンダリングできます。

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ja.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask
 app = Flask(__name__)
 @app.route('/')
 def index():
    return render_template(‘hello.html’)
 if __name__ == '__main__':
    app.run(debug=True)

Flaskは、スクリプトが所在する同一のフォルダー内のtemplatesフォルダーにあるHTMLファイルを探します。以下のアプリケーションディレクトリ構造を使用するテンプレートアプリケーションはこのように見えます -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ja.oldtoolbag.com
# Date : 2020-08-08
app.py
 hello.py
     templates
         hello.html
         register.html
         ....

「ウェブテンプレートシステム」とは、HTMLスクリプトをデザインし、変数データを動的に挿入できることを意味します。ウェブテンプレートシステムは、テンプレートエンジン、ある種のデータソース、およびテンプレートプロセッサから構成されています。

Flaskはjingaを使用2テンプレートエンジン。ウェブテンプレートは、変数や表現(この場合、Python表現)のためのHTML構文の散布占位符を含みます。これらの変数や表現はテンプレートが表示される際に値に置き換えられます。

以下のコードはテンプレート( templates)フォルダーに保存します: hello.html

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ja.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask HTTPリクエストメソッド処理</title>
 </head>
    <body>
       <h1>Hello {{ name }}!</h1>
    </body>
 </html>

次に、以下のコードを保存します app.pyファイル中、Python shellで実行 -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ja.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask, render_template
 app = Flask(__name__)
 @app.route('/hello/<user>')
 def hello_name(user):
     return render_template('hello.html', name = user)}
 if __name__ == '__main__':
     app.run(debug=True)

開発サーバーが動作を始めた際に、ブラウザを開き、以下のURLにアクセスします - http://localhost:5000/hello/maxsu

URLの可変部分は{{name}}占位符に挿入されます。

Jinja2テンプレートエンジンは以下の区切り記号を使用してHTMLからエスケープします。

{% ... %} 多行文用 {{ ... }} 表現をテンプレートに印刷出力するため {# ... #} テンプレート出力に含まれないコメント用 # ... ## 単一行文用

以下の例では、テンプレート内で条件文を使用する方法を示します。hello()関数のURLルールは整数パラメータを受け取り、hello.htmlテンプレートに渡されます。その中で、受け取った数字(スコア)の値が比較(大きいか小さいか)されます。50),そのため、HTMLで条件付きのレンダリングが行われました。

Pythonスクリプトは以下の通りです -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ja.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask, render_template
 app = Flask(__name__)
 @app.route('/hello/<int:score>')
 def hello_name(score):
     return render_template('hello.html', marks = score)
 if __name__ == '__main__':
     app.run(debug=True)

テンプレートファイル: hello.html のHTMLテンプレートスクリプトは以下の通りです -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ja.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flaskテンプレートサンプル</title>
 </head>
    <body>
       {% if marks}50 %}
       <h1> テストに合格しました!</h1>
       {% else %}
       <h1>テストに失敗しました!</h1>
       {% endif %}
    </body>
 </html>

注意していただきたいのは、条件文if-elseおよびendifは、区切り記号{%..。%}内に含まれています。

Pythonスクリプトを実行し、URLをアクセスしてください => http://localhost/hello/60、その後 http://localhost/hello/59を条件にしてHTML出力を確認できます。

Pythonのループ構造はテンプレート内部でも使用できます。以下のスクリプトでは、ブラウザでURLを開いた場合、以下のURL => http:// localhost:5000/result時に、result()関数は辞書オブジェクトをテンプレートファイルに送信します: results.html

result.html テンプレートの部分では、forループを使用して、辞書オブジェクトresult{}のキーと値のペアをHTMLテーブルのセルとして表示します。

Pythonシェルから以下のコードを実行します。

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ja.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask, render_template
 app = Flask(__name__)
 @app.route('/result')
 def result():
     dict = {'phy':59,'che':60,'maths':90
     return render_template('result.html', result=dict}}
 if __name__ == '__main__':
     app.run(debug=True)

以下のHTMLスクリプトをテンプレートフォルダーに保存します( templates)内のテンプレートファイル: result.html

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ja.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flaskテンプレートサンプル</title>
 </head>
    <body>
       <table border= 1>
          {% for key, value in result.items() %}
             <tr>
                <th> {{ key }} </th>
                <td> {{ value }} </td>
             </tr>
          {% endfor %}
       </table>
    </body>
 </html>

ここでは、Forループに対応するPython文は{%...%}に含まれ、キーと値は{{}}に置かれます。

開発が開始され、ブラウザでhttp:を開き、//localhost:5000/以下の出力を得るためにはresultを使用してください。