0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flask入門➂:render_template編

Posted at

はじめに

前回はroute()デコレータについて学習しました。
※前回の記事はこちら

今回はHTMLファイルの生成に役立つrender_templateについて学びます。

render_template()

Flaskではjinja2テンプレートエンジンを利用して、HTMLファイルを生成できます。
jinja2テンプレートをレンダリングするのに、render_template()を使用します。

hello.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
@app.route("/<username>/")
def hello(username=None):
    return render_template("hello.html", username=username)

上記のrender_template("hello.html", username=username)でレンダリングを行っています。
引数として設定しているのは、対象のHTMLファイル名と受け渡す変数です。
HTMLファイルは./templates/配下に格納しましょう。

$ ls -lR
total 12
-rw-r--r-- 1 xxxxx xxxxx  194 Dec 20 15:02 hello.py
drwxr-xr-x 2 xxxxx xxxxx 4096 Dec 20 22:22 templates

./templates:
total 4
-rw-r--r-- 1 xxxxx xxxxx 305 Dec 21 15:04 hello.html

templates配下に作成するHTMLファイルはjinja2構文で記載ができます。
これにより、HTMLファイルで変数の展開や、条件分岐、loop処理など実現可能になります。
凝った使い方はまだ理解できていないので、ドキュメントを載せておきます。

hello.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Flask</title>
</head>
<body>
  {%- if username %}
    <h1>Hello, {{ username }}!</h1>
  {%- else %}
    <h1>Hello, Guest!</h1>
  {%- endif %}
</body>
</html>

上記は変数(username)の値に応じて、見出しの内容が変わるコードになります。

テンプレートの継承

テンプレートでは、継承という機能を利用することができます。
雛形となる親テンプレートを作成し、それを基に子テンプレートで必要な箇所を上書きします。
これにより、HTMLの共通部分を親テンプレートのみで管理することができます。

親テンプレートのサンプルは以下です。
{% block %}タグで、どの箇所を子テンプレートで上書きするか定義しています。

laybout.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}{% endblock %} - Flask</title>
</head>
<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

子テンプレートのサンプルは以下です。

  • {% extends %}タグで親テンプレートを指定
  • {% block %}タグで上書きする値を指定
hello.html
{% extends "layout.html" %}

{% block title %}Hello{% endblock %}
{% block content %}
  {%- if username -%}
    <h1>Hello, {{ username }}!</h1>
  {%- else -%}
    <h1>Hello, World!</h1>
  {%- endif -%}
{% endblock %}

実際に以下のコードを使用して、Flaskを起動します。

hello.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
@app.route("/<username>/")
def hello(username=None):
    return render_template("hello.html", username=username)

ブラウザからアクセスすると、継承されたテンプレートの内容が反映されていることがわかります。
image.png

ページのソースを表示すると継承されていることがコードベースでわかります。
image.png

CSSの適用

HTMLファイルは通常templatesに配置しますが、cssなどの静的ファイルはstaticフォルダに配置するのが慣例です。
配置したファイルはテンプレートから以下のように参照します。

{{ url_for('static', filename='ファイル名') }}
laybout.html
<head>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <title>タイトル</title>
</head>

まとめ

今回はHTMLを生成するのに役立つrender_templateの使い方について学びました。
HTMLやCSS自体普段触ることがないので、Webページを作成するにも手間取りそうです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?