extends

The extends tag can be used to extend a template from another one.

extends タグを使用して、別のテンプレートからテンプレートを拡張できます。

Note

ノート

Like PHP, Twig does not support multiple inheritance. So you can only have one extends tag called per rendering. However, Twig supports horizontal reuse.

PHP と同様に、Twig は多重継承をサポートしていません。したがって、レンダリングごとに呼び出される extends タグは 1 つだけです。ただし、Twig は horizo​​ntalreuse をサポートしています。

Let's define a base template, base.html, which defines a simple HTML skeleton document:

単純な HTML スケルトン ドキュメントを定義する基本テンプレート base.html を定義しましょう。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
    <head>
        {% block head %}
            <link rel="stylesheet" href="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 2011 by <a href="http://domain.invalid/">you</a>.
            {% endblock %}
        </div>
    </body>
</html>

In this example, the block tags define four blocks that child templates can fill in.

この例では、ブロック タグは、子テンプレートが入力できる 4 つのブロックを定義します。

All the block tag does is to tell the template engine that a child template may override those portions of the template.

block タグが行うことは、子テンプレートがテンプレートのこれらの部分をオーバーライドする可能性があることをテンプレート エンジンに伝えることだけです。

Child Template

A child template might look like this:

子テンプレートは次のようになります。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{% extends "base.html" %}

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

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 should be the first tag in the template.

extends タグがここでの鍵です。これは、このテンプレートが別のテンプレートを「拡張」することをテンプレート エンジンに伝えます。テンプレート システムがこのテンプレートを評価するとき、最初に親を見つけます。 extends タグは、テンプレートの最初のタグにする必要があります。

Note that since the child template doesn't define the footer block, the value from the parent template is used instead.

子テンプレートはフッター ブロックを定義しないため、代わりに親テンプレートの値が使用されることに注意してください。

You can't define multiple block tags with the same name in the same template. This limitation exists because a block tag works in "both" directions. That is, a block tag doesn't just provide a hole to fill - it also defines the content that fills the hole in the parent. If there were two similarly-named block tags in a template, that template's parent wouldn't know which one of the blocks' content to use.

同じテンプレートに同じ名前のブロック タグを複数定義することはできません。この制限が存在するのは、ブロック タグが「双方向」で機能するためです。つまり、ブロック タグは埋める穴を提供するだけでなく、親の穴を埋めるコンテンツも定義します。テンプレートに同じような名前のブロック タグが 2 つある場合、そのテンプレートの親はブロックのコンテンツのどれを使用するかわかりません。

If you want to print a block multiple times you can however use the block function:

ただし、ブロックを複数回印刷したい場合は、ブロック関数を使用できます。
1
2
3
<title>{% block title %}{% endblock %}</title>
<h1>{{ block('title') }}</h1>
{% block body %}{% endblock %}

Parent Blocks

It's possible to render the contents of the parent block by using the parent function. This gives back the results of the parent block:

親関数を使用して、親ブロックの内容をレンダリングすることができます。これにより、親ブロックの結果が返されます。
1
2
3
4
5
{% block sidebar %}
    <h3>Table Of Contents</h3>
    ...
    {{ parent() }}
{% endblock %}

Named Block End-Tags

Twig allows you to put the name of the block after the end tag for better readability (the name after the endblock word must match the block name):

Twig では、読みやすくするために終了タグの後にブロックの名前を付けることができます (終了ブロックの単語の後の名前はブロック名と一致する必要があります)。
1
2
3
4
5
{% block sidebar %}
    {% block inner_sidebar %}
        ...
    {% endblock inner_sidebar %}
{% endblock sidebar %}

Block Nesting and Scope

Blocks can be nested for more complex layouts. Per default, blocks have access to variables from outer scopes:

ブロックをネストして、より複雑なレイアウトにすることができます。デフォルトでは、ブロックは外側のスコープから変数にアクセスできます。
1
2
3
{% for item in seq %}
    <li>{% block loop_item %}{{ item }}{% endblock %}</li>
{% endfor %}

Block Shortcuts

For blocks with little content, it's possible to use a shortcut syntax. The following constructs do the same thing:

コンテンツの少ないブロックの場合、ショートカット構文を使用できます。次の構成体は同じことを行います。
1
2
3
{% block title %}
    {{ page_title|title }}
{% endblock %}
1
{% block title page_title|title %}

Dynamic Inheritance

Twig supports dynamic inheritance by using a variable as the base template:

Twig は、変数を基本テンプレートとして使用することにより、動的継承をサポートします。
1
{% extends some_var %}

If the variable evaluates to a \Twig\Template or a \Twig\TemplateWrapper instance, Twig will use it as the parent template:

変数が \Twig\Template または \Twig\TemplateWrapperinstance に評価される場合、Twig はそれを親テンプレートとして使用します。
1
2
3
4
5
// {% extends layout %}

$layout = $twig->load('some_layout_template.twig');

$twig->display('template.twig', ['layout' => $layout]);

You can also provide a list of templates that are checked for existence. The first template that exists will be used as a parent:

存在を確認するテンプレートのリストを提供することもできます。存在する最初のテンプレートが親として使用されます。
1
{% extends ['layout.html', 'base_layout.html'] %}

Conditional Inheritance

As the template name for the parent can be any valid Twig expression, it's possible to make the inheritance mechanism conditional:

親のテンプレート名は任意の有効な Twig 式にすることができるため、継承メカニズムを条件付きにすることができます。
1
{% extends standalone ? "minimum.html" : "base.html" %}

In this example, the template will extend the "minimum.html" layout template if the standalone variable evaluates to true, and "base.html" otherwise.

この例では、スタンドアロン変数が true と評価された場合、テンプレートは "minimum.html" レイアウト テンプレートを拡張し、そうでない場合は "base.html" を拡張します。

How do blocks work?

A block provides a way to change how a certain part of a template is rendered but it does not interfere in any way with the logic around it.

ブロックは、テンプレートの特定の部分がどのようにレンダリングされるかを変更する方法を提供しますが、その周りのロジックにはまったく干渉しません。

Let's take the following example to illustrate how a block works and more importantly, how it does not work:

次の例を見て、ブロックがどのように機能するか、さらに重要なことに、どのように機能しないかを説明しましょう。
1
2
3
4
5
6
7
{# base.twig #}
{% for post in posts %}
    {% block post %}
        <h1>{{ post.title }}</h1>
        <p>{{ post.body }}</p>
    {% endblock %}
{% endfor %}

If you render this template, the result would be exactly the same with or without the block tag. The block inside the for loop is just a way to make it overridable by a child template:

このテンプレートをレンダリングすると、block タグがあってもなくても結果はまったく同じになります。 for ループ内のブロックは、子テンプレートによってオーバーライド可能にする方法にすぎません。
1
2
3
4
5
6
7
8
9
{# child.twig #}
{% extends "base.twig" %}

{% block post %}
    <article>
        <header>{{ post.title }}</header>
        <section>{{ post.text }}</section>
    </article>
{% endblock %}

Now, when rendering the child template, the loop is going to use the block defined in the child template instead of the one defined in the base one; the executed template is then equivalent to the following one:

ここで、子テンプレートをレンダリングするとき、ループは基本テンプレートで定義されたブロックではなく、子テンプレートで定義されたブロックを使用します。実行されたテンプレートは、次のものと同等です。
1
2
3
4
5
6
{% for post in posts %}
    <article>
        <header>{{ post.title }}</header>
        <section>{{ post.text }}</section>
    </article>
{% endfor %}

Let's take another example: a block included within an if statement:

別の例を見てみましょう: if ステートメント内に含まれるブロック:
1
2
3
4
5
6
7
{% if posts is empty %}
    {% block head %}
        {{ parent() }}

        <meta name="robots" content="noindex, follow">
    {% endblock head %}
{% endif %}

Contrary to what you might think, this template does not define a block conditionally; it just makes overridable by a child template the output of what will be rendered when the condition is true.

お考えかもしれませんが、このテンプレートはブロックを条件付きで定義しません。条件が真の場合にレンダリングされるものの出力を子テンプレートによってオーバーライド可能にするだけです。

If you want the output to be displayed conditionally, use the following instead:

出力を条件付きで表示する場合は、代わりに次を使用します。
1
2
3
4
5
6
7
{% block head %}
    {{ parent() }}

    {% if posts is empty %}
        <meta name="robots" content="noindex, follow">
    {% endif %}
{% endblock head %}

See also

こちらもご覧ください

block, block, parent, use

ブロック、ブロック、親、使用