Jinja2メモ

最近、FlaskでWebアプリを書いたりしていたので、ちょっとずつ勉強した内容をまとめてみる。 今回はFlaskで採用されているJinja2(テンプレートエンジン)についてのメモ。

条件分岐

{% if flag == 1 %}
    <p>あいうえお</p>
{% elif flag == 2 %}
    <p>かきくけこ</p>
{% else %}
    <p>さしすせそ</p>
{% endif %}

リストでループ

{% for comment in comments %}
    <p>{{loop.index}} : {{comment}}</p>
{% endfor %}

上の例のようにloop.indexもしくはloop.index0というループ変数が使えます。 loop.index0は0から,loop.indexは1から始まります。 その他にもloop.lengthとかloop.cycle等があるので、詳しくはJinja2 Documentation List of Control Structureを参照.

commentsの要素数が0の時に、別の文字列を表示したい場合は下のようにします.

{% for comment in comments %}
    <p>{{loop.index}} : {{comment}}</p>
{% else %}
<p>コメントはありません</p>
{% endfor %}

フィルタ

{{ comments|length }}

上の例ではcommentsの要素数を表示します.他にも便利なフィルタがたくさんあるので、詳しくはJinja2 Documentation List of Builtin Filtersを参照.

指定回数ループ

{% for n in range(31) %}
    <p>{{n+1}}</p>
{% endfor %}

フラッシュメッセージ

フラッシュでメッセージ等を入れるためには、htmlファイルに↓を追加します。

{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

プログラム側では↓のように使います。

@app.route('/login')
def login():
    """Login"""
    ...
    flash(u'ログイン成功!' )
    return redirect(url_for('mypage'))

共通部分の定義

headやヘッダー、フッター等、どのページでも使うような共通部分は、layout.htmlとして定義しておく。

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" type="text/css" >
        <link rel="shortcut icon" href="{{ url_for('static',filename='favicon.ico') }}" />
        <link href="/static/css/bootstrap.min.css" rel="stylesheet" media="screen">
        <link href="/static/css/bootstrap-responsive.css" rel="stylesheet">
        <title>タイトル</title>
    </head>
    <body>
        <div class="container" style="padding:20px 0">
            <div id="header"><h1 class="text-center">ヘッダー</h1></div>

            <!-- Display flashed messages with categories -->
            {% with messages = get_flashed_messages() %}
                {% if messages %}
                    <ul class=flashes>
                    {% for message in messages %}
                        <li>{{ message }}</li>
                    {% endfor %}
                    </ul>
                {% endif %}
            {% endwith %}

            <!-- Body Block -->
            {% block body %}{% endblock %}

            <div class="footer">
                <p>フッター</p>
            </div>
        </div> <!-- /container -->
</body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
</html>

layout.htmlさえあれば、後は書くhtmlファイルを↓のように記述する。

{% extends "layout.html" %}
{% block body %}

<!-- この中にコードを書いていく -->

{% endblock %}

参考

Flask Web Development: Developing Web Applications with Python

Flask Web Development: Developing Web Applications with Python