テンプレートの継承 Template Inheritance

Jinjの最も強力な部分はテンプレート継承です。テンプレート継承は、自分のサイトで共通な要素をすべて含み、子テンプレートが上書きできるblocksを定義する、ベースの「骨組み(skelton)」テンプレートを構築できるようにします The most powerful part of Jinja is template inheritance. Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines **blocks** that child templates can override.

複雑に聞こえますがとても基本的なものです。例を使って始めれば最も容易に理解できるでしょう。 Sounds complicated but is very basic. It's easiest to understand it by starting with an example.

ベースのテンプレート Base Template

このテンプレートは、layout.htmlと呼びますが、シンプルな2列のページ用に使える、シンプルなHTMLの骨組みになるドキュメントを定義します。空のブロックをコンテンツで埋めるのは「子」テンプレートの仕事です: This template, which we'll call :file:`layout.html`, defines a simple HTML skeleton document that you might use for a simple two-column page. It's the job of "child" templates to fill the empty blocks with content:

<!doctype html>
<html>
  <head>
    {% block head %}
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <title>{% block title %}{% endblock %} - My Webpage</title>
    {% endblock %}
  </head>
  <body>
    <div id="content">{% block content %}{% endblock %}</div>
    <div id="footer">
      {% block footer %}
      &copy; Copyright 2010 by <a href="http://domain.invalid/">you</a>.
      {% endblock %}
    </div>
  </body>
</html>

この例では、{% block %}タグは子テンプレートで埋めることが可能な4つのブロックを定義します。すべてのblockタグが行うことは、子テンプレートがテンプレートのそれらの場所を上書きするかもしれないと、テンプレート・エンジンに伝えることです。 In this example, the ``{% block %}`` tags define four blocks that child templates can fill in. All the `block` tag does is tell the template engine that a child template may override those portions of the template.

子テンプレート Child Template

子テンプレートは以下のようになるでしょう: A child template might look like this:

{% extends "layout.html" %}
{% block title %}Index{% endblock %}
{% block head %}
  {{ super() }}
  <style type="text/css">
    .important { color: #336699; }
  </style>
{% endblock %}
{% block content %}
  <h1>Index</h1>
  <p class="important">
    Welcome on my awesome homepage.
{% endblock %}

{% extends %}タグがここでは鍵になります。それはテンプレート・エンジンに、このテンプレートは他のテンプレートを「拡張」することを伝えます。テンプレート・システムがこのテンプレートを評価するとき、最初に親の場所を見つけます。extendsタグはテンプレートの最初のタグである必要があります。親テンプレートの中で定義されたブロックの内容を表示(render)するには、{{ super() }}を使います。 The ``{% extends %}`` tag is the key here. It tells the template engine that this template "extends" another template. When the template system evaluates this template, first it locates the parent. The extends tag must be the first tag in the template. To render the contents of a block defined in the parent template, use ``{{ super() }}``.