Twig for Template Designers

This document describes the syntax and semantics of the template engine and will be most useful as reference to those creating Twig templates.

このドキュメントは、テンプレート エンジンの構文とセマンティクスについて説明しており、Twig テンプレートを作成する際のリファレンスとして最も役立ちます。

Synopsis

A template is a regular text file. It can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). It doesn't have a specific extension, .html or .xml are just fine.

テンプレートは通常のテキスト ファイルです。テキストベースのフォーマット (HTML、XML、CSV、LaTeX など) を生成できます。特定の拡張子はありません。.html または .xml で十分です。

A template contains variables or expressions, which get replaced with values when the template is evaluated, and tags, which control the template's logic.

テンプレートには、テンプレートの評価時に値に置き換えられる変数または式と、テンプレートのロジックを制御するタグが含まれます。

Below is a minimal template that illustrates a few basics. We will cover further details later on:

以下は、いくつかの基本を示す最小限のテンプレートです。詳細については、後で説明します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
    <head>
        <title>My Webpage</title>
    </head>
    <body>
        <ul id="navigation">
        {% for item in navigation %}
            <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
        {% endfor %}
        </ul>

        <h1>My Webpage</h1>
        {{ a_variable }}
    </body>
</html>

There are two kinds of delimiters: {% ... %} and {{ ... }}. The first one is used to execute statements such as for-loops, the latter outputs the result of an expression.

区切り文字には、{% ... %} と {{ ... }} の 2 種類があります。前者は for ループなどのステートメントを実行するために使用され、後者は式の結果を出力します。

IDEs Integration

Many IDEs support syntax highlighting and auto-completion for Twig:

多くの IDE は、Twig の構文の強調表示と自動補完をサポートしています。
  • Textmate via the Twig bundle
    Twig バンドルを介した Textmate
  • Vim via the Jinja syntax plugin or the vim-twig plugin
    Jinja 構文プラグインまたは vim-twig プラグイン経由の Vim
  • Netbeans via the Twig syntax plugin (until 7.1, native as of 7.2)
    Twig 構文プラグインを介した Netbeans (7.1 まで、7.2 以降はネイティブ)
  • PhpStorm (native as of 2.1)
    PhpStorm (2.1 でネイティブ)
  • Eclipse via the Twig plugin
    Twig プラグイン経由の Eclipse
  • Sublime Text via the Twig bundle
    Twig バンドルによる Sublime Text
  • GtkSourceView via the Twig language definition (used by gedit and other projects)
    Twig 言語定義による GtkSourceView (gedit および他のプロジェクトで使用)
  • Coda and SubEthaEdit via the Twig syntax mode
    Twig 構文モードによる Coda と SubEthaEdit
  • Coda 2 via the other Twig syntax mode
    他の Twig 構文モード経由の Coda 2
  • Komodo and Komodo Edit via the Twig highlight/syntax check mode
    Twig ハイライト/構文チェック モードによる Komodo および Komodo Edit
  • Notepad++ via the Notepad++ Twig Highlighter
    Notepad++ Twig Highlighter 経由の Notepad++
  • Emacs via web-mode.el
    web-mode.el 経由の Emacs
  • Atom via the PHP-twig for atom
    Atom 用の PHP-twig 経由の Atom
  • Visual Studio Code via the Twig pack
    Twig パック経由の Visual Studio Code

Also, TwigFiddle is an online service that allows you to execute Twig templates from a browser; it supports all versions of Twig.

また、TwigFiddle は、ブラウザから Twig テンプレートを実行できるオンライン サービスです。 Twig のすべてのバージョンをサポートします。

Variables

The application passes variables to the templates for manipulation in the template. Variables may have attributes or elements you can access, too. The visual representation of a variable depends heavily on the application providing it.

アプリケーションは、テンプレートでの操作のためにテンプレートに変数を渡します。変数には、アクセスできる属性または要素も含まれる場合があります。変数のビジュアル表現は、それを提供するアプリケーションに大きく依存します。

Use a dot (.) to access attributes of a variable (methods or properties of a PHP object, or items of a PHP array):

ドット (.) を使用して、変数の属性 (PHP オブジェクトのメソッドまたはプロパティ、または PHP 配列の項目) にアクセスします。
1
{{ foo.bar }}

Note

ノート

It's important to know that the curly braces are not part of the variable but the print statement. When accessing variables inside tags, don't put the braces around them.

中括弧は変数の一部ではなく、print ステートメントの一部であることを知っておくことが重要です。タグ内の変数にアクセスするときは、括弧で囲まないでください。
実装

For convenience's sake foo.bar does the following things on the PHP layer:

便宜上、foo.bar は PHPlayer で次のことを行います。
  • check if foo is an array and bar a valid element;
    foo が配列であり、bar が有効な要素であるかどうかを確認します。
  • if not, and if foo is an object, check that bar is a valid property;
    そうでない場合、かつ foo がオブジェクトの場合は、bar が有効なプロパティであることを確認します。
  • if not, and if foo is an object, check that bar is a valid method (even if bar is the constructor - use __construct() instead);
    そうでない場合、かつ foo がオブジェクトの場合は、bar が有効なメソッドであることを確認します (bar がコンストラクターの場合でも、代わりに __construct() を使用してください)。
  • if not, and if foo is an object, check that getBar is a valid method;
    そうでない場合、かつ foo がオブジェクトの場合は、getBar が有効なメソッドであることを確認します。
  • if not, and if foo is an object, check that isBar is a valid method;
    そうでない場合、かつ foo がオブジェクトの場合は、isBar が有効なメソッドであることを確認します。
  • if not, and if foo is an object, check that hasBar is a valid method;
    そうでない場合、かつ foo がオブジェクトの場合は、hasBar が有効なメソッドであることを確認します。
  • if not, return a null value.
    そうでない場合は、null 値を返します。

Twig also supports a specific syntax for accessing items on PHP arrays, foo['bar']:

Twig は、PHP 配列の項目にアクセスするための特定の構文 foo['bar'] もサポートしています。
  • check if foo is an array and bar a valid element;
    foo が配列であり、bar が有効な要素であるかどうかを確認します。
  • if not, return a null value.
    そうでない場合は、null 値を返します。

If a variable or attribute does not exist, you will receive a null value when the strict_variables option is set to false; alternatively, if strict_variables is set, Twig will throw an error (see environment options).

変数または属性が存在しない場合、strict_variables オプションが false に設定されていると、null 値が返されます。あるいは、strict_variablesis が設定されている場合、Twig はエラーをスローします (環境オプションを参照)。

Note

ノート

If you want to access a dynamic attribute of a variable, use the attribute function instead.

変数の動的属性にアクセスする場合は、代わりに属性関数を使用してください。

The attribute function is also useful when the attribute contains special characters (like - that would be interpreted as the minus operator):

属性関数は、属性に特殊文字 (マイナス演算子として解釈される - など) が含まれている場合にも役立ちます。
1
2
{# equivalent to the non-working foo.data-foo #}
{{ attribute(foo, 'data-foo') }}

Global Variables

The following variables are always available in templates:

次の変数は、テンプレートで常に使用できます。
  • _self: references the current template name;
    _self: 現在のテンプレート名を参照します。
  • _context: references the current context;
    _context: 現在のコンテキストを参照します。
  • _charset: references the current charset.
    _charset: 現在の文字セットを参照します。

Setting Variables

You can assign values to variables inside code blocks. Assignments use the set tag:

コード ブロック内の変数に値を割り当てることができます。課題では set タグを使用します。
1
2
3
{% set foo = 'foo' %}
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}

Filters

Variables can be modified by filters. Filters are separated from the variable by a pipe symbol (|). Multiple filters can be chained. The output of one filter is applied to the next.

変数はフィルターによって変更できます。フィルターはパイプ記号 (|) で変数と区切られます。複数のフィルターを連鎖させることができます。 1 つのフィルタの出力が次のフィルタに適用されます。

The following example removes all HTML tags from the name and title-cases it:

次の例では、name と title-casesit からすべての HTML タグを削除します。
1
{{ name|striptags|title }}

Filters that accept arguments have parentheses around the arguments. This example joins the elements of a list by commas:

引数を受け入れるフィルターには、引数が括弧で囲まれています。この例では、リストの要素をコンマで結合しています。
1
{{ list|join(', ') }}

To apply a filter on a section of code, wrap it with the apply tag:

コードのセクションにフィルターを適用するには、apply タグで囲みます。
1
2
3
{% apply upper %}
    This text becomes uppercase
{% endapply %}

Go to the filters page to learn more about built-in filters.

組み込みフィルターの詳細については、フィルター ページに移動してください。

Functions

Functions can be called to generate content. Functions are called by their name followed by parentheses (()) and may have arguments.

関数を呼び出してコンテンツを生成できます。関数は、名前の後に括弧 (()) を付けて呼び出され、引数を持つ場合があります。

For instance, the range function returns a list containing an arithmetic progression of integers:

たとえば、 range 関数は、整数の算術進行を含むリストを返します。
1
2
3
{% for i in range(0, 3) %}
    {{ i }},
{% endfor %}

Go to the functions page to learn more about the built-in functions.

関数ページに移動して、組み込み関数の詳細を確認してください。

Named Arguments

1
2
3
{% for i in range(low=1, high=10, step=2) %}
    {{ i }},
{% endfor %}

Using named arguments makes your templates more explicit about the meaning of the values you pass as arguments:

名前付き引数を使用すると、引数として渡す値の意味がテンプレートにより明確になります。
1
2
3
4
5
{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}

{# versus #}

{{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }}

Named arguments also allow you to skip some arguments for which you don't want to change the default value:

名前付き引数を使用すると、デフォルト値を変更したくないいくつかの引数をスキップすることもできます:
1
2
3
4
5
{# the first argument is the date format, which defaults to the global date format if null is passed #}
{{ "now"|date(null, "Europe/Paris") }}

{# or skip the format value by using a named argument for the time zone #}
{{ "now"|date(timezone="Europe/Paris") }}

You can also use both positional and named arguments in one call, in which case positional arguments must always come before named arguments:

1 回の呼び出しで位置引数と名前付き引数の両方を使用することもできます。この場合、位置引数は常に名前付き引数の前に来る必要があります。
1
{{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }}

Tip

ヒント

Each function and filter documentation page has a section where the names of all arguments are listed when supported.

各関数とフィルターのドキュメント ページには、サポートされているすべての引数の名前がリストされているセクションがあります。

Control Structure

A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elseif/else), for-loops, as well as things like blocks. Control structures appear inside {% ... %} blocks.

制御構造とは、プログラムの流れを制御するすべてのものを指します - 条件文 (つまり、if/elseif/else)、for ループ、ブロックなどです。制御構造は {% ... %} ブロック内に表示されます。

For example, to display a list of users provided in a variable called users, use the for tag:

たとえば、users という変数で指定されたユーザーのリストを表示するには、for タグを使用します。
1
2
3
4
5
6
<h1>Members</h1>
<ul>
    {% for user in users %}
        <li>{{ user.username|e }}</li>
    {% endfor %}
</ul>

The if tag can be used to test an expression:

if タグを使用して、式をテストできます。
1
2
3
4
5
6
7
{% if users|length > 0 %}
    <ul>
        {% for user in users %}
            <li>{{ user.username|e }}</li>
        {% endfor %}
    </ul>
{% endif %}

Go to the tags page to learn more about the built-in tags.

組み込みタグの詳細については、タグ ページに移動してください。

Comments

To comment-out part of a line in a template, use the comment syntax {# ... #}. This is useful for debugging or to add information for other template designers or yourself:

テンプレートの行の一部をコメントアウトするには、コメント構文 {# ...#} を使用します。これは、デバッグしたり、他のテンプレート設計者や自分自身のために情報を追加したりするのに役立ちます:
1
2
3
4
5
{# note: disabled template because we no longer use this
    {% for user in users %}
        ...
    {% endfor %}
#}

Including other Templates

The include function is useful to include a template and return the rendered content of that template into the current one:

include 関数は、テンプレートをインクルードし、そのテンプレートのレンダリングされたコンテンツを現在のテンプレートに返すのに役立ちます。
1
{{ include('sidebar.html') }}

By default, included templates have access to the same context as the template which includes them. This means that any variable defined in the main template will be available in the included template too:

デフォルトでは、含まれるテンプレートは、それらを含むテンプレートと同じコンテキストにアクセスできます。これは、メイン テンプレートで定義されたすべての変数が、インクルードされたテンプレートでも使用できることを意味します。
1
2
3
{% for box in boxes %}
    {{ include('render_box.html') }}
{% endfor %}

The included template render_box.html is able to access the box variable.

含まれているテンプレート render_box.html は、ボックス変数にアクセスできます。

The name of the template depends on the template loader. For instance, the \Twig\Loader\FilesystemLoader allows you to access other templates by giving the filename. You can access templates in subdirectories with a slash:

テンプレートの名前は、テンプレート ローダーによって異なります。たとえば、\Twig\Loader\FilesystemLoader では、ファイル名を指定することで他のテンプレートにアクセスできます。スラッシュを使用して、サブディレクトリ内のテンプレートにアクセスできます。
1
{{ include('sections/articles/sidebar.html') }}

This behavior depends on the application embedding Twig.

この動作は、Twig を組み込んだアプリケーションに依存します。

Template Inheritance

The most powerful part of Twig 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.

Twig の最も強力な部分は、テンプレートの継承です。テンプレートの継承により、サイトのすべての共通要素を含み、子テンプレートがオーバーライドできるブロックを定義する基本の「スケルトン」テンプレートを構築できます。

It's easier to understand the concept by starting with an example.

例から始めると、概念を理解しやすくなります。

Let's define a base template, base.html, which defines an HTML skeleton document that might be used for a two-column page:

ベース テンプレート base.html を定義しましょう。これは、2 列のページに使用できる 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. All the block tag does is to tell the template engine that a child template may override those portions of the template.

この例では、ブロック タグは、子テンプレートが入力できる 4 つのブロックを定義します。ブロック タグが行うことは、子テンプレートがテンプレートのこれらの部分をオーバーライドできることをテンプレート エンジンに伝えることだけです。

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 to 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.

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

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 %}

Tip

ヒント

The documentation page for the extends tag describes more advanced features like block nesting, scope, dynamic inheritance, and conditional inheritance.

extends タグのドキュメント ページでは、ブロックのネスト、スコープ、動的継承、条件付き継承などのより高度な機能について説明しています。

Note

ノート

Twig also supports multiple inheritance via "horizontal reuse" with the help of the use tag.

Twig は、use タグを使用した「水平再利用」による多重継承もサポートしています。

HTML Escaping

When generating HTML from templates, there's always a risk that a variable will include characters that affect the resulting HTML. There are two approaches: manually escaping each variable or automatically escaping everything by default.

テンプレートから HTML を生成する場合、結果の HTML に影響を与える文字が変数に含まれるリスクが常にあります。 2 つのアプローチがあります。各変数を手動でエスケープする方法と、デフォルトですべてを自動的にエスケープする方法です。

Twig supports both, automatic escaping is enabled by default.

Twig は両方をサポートしており、自動エスケープはデフォルトで有効になっています。

The automatic escaping strategy can be configured via the autoescape option and defaults to html.

自動エスケープ戦略は autoescape オプションで設定でき、デフォルトは html です。

Working with Manual Escaping

If manual escaping is enabled, it is your responsibility to escape variables if needed. What to escape? Any variable that comes from an untrusted source.

手動エスケープが有効になっている場合は、必要に応じて変数をエスケープする必要があります。何を逃げる?信頼できないソースからの変数。

Escaping works by using the escape or e filter:

エスケープは、escape または e フィルターを使用して機能します。
1
{{ user.username|e }}

By default, the escape filter uses the html strategy, but depending on the escaping context, you might want to explicitly use another strategy:

デフォルトでは、エスケープ フィルタは html 戦略を使用しますが、エスケープ コンテキストによっては、明示的に別の戦略を使用することをお勧めします。
1
2
3
4
{{ user.username|e('js') }}
{{ user.username|e('css') }}
{{ user.username|e('url') }}
{{ user.username|e('html_attr') }}

Working with Automatic Escaping

Whether automatic escaping is enabled or not, you can mark a section of a template to be escaped or not by using the autoescape tag:

自動エスケープが有効になっているかどうかに関係なく、autoescape タグを使用して、テンプレートのセクションをエスケープするかどうかをマークできます。
1
2
3
{% autoescape %}
    Everything will be automatically escaped in this block (using the HTML strategy)
{% endautoescape %}

By default, auto-escaping uses the html escaping strategy. If you output variables in other contexts, you need to explicitly escape them with the appropriate escaping strategy:

デフォルトでは、自動エスケープは html エスケープ戦略を使用します。他のコンテキストで変数を出力する場合は、適切なエスケープ戦略で明示的にエスケープする必要があります。
1
2
3
{% autoescape 'js' %}
    Everything will be automatically escaped in this block (using the JS strategy)
{% endautoescape %}

Escaping

It is sometimes desirable or even necessary to have Twig ignore parts it would otherwise handle as variables or blocks. For example if the default syntax is used and you want to use {{ as raw string in the template and not start a variable you have to use a trick.

Twig が変数またはブロックとして処理する部分を無視することが望ましい、または必要でさえある場合があります。たとえば、デフォルトの構文が使用されていて、テンプレートで {{ を生の文字列として使用し、変数を開始したくない場合は、トリックを使用する必要があります。

The easiest way is to output the variable delimiter ({{) by using a variable expression:

最も簡単な方法は、変数式を使用して変数区切り文字 ({{) を出力することです。
1
{{ '{{' }}

For bigger sections it makes sense to mark a block verbatim.

より大きなセクションの場合、blockverbatim をマークすることは理にかなっています。

Macros

Macros are comparable with functions in regular programming languages. They are useful to reuse HTML fragments to not repeat yourself. They are described in the macro tag documentation.

マクロは、通常のプログラミング言語の関数と同等です。同じことを繰り返さないように、HTML フラグメントを再利用するのに役立ちます。これらは、マクロ タグのドキュメントで説明されています。

Expressions

Twig allows expressions everywhere.

Twig ではどこでも式を使用できます。

Note

ノート

The operator precedence is as follows, with the lowest-precedence operators listed first: ?: (ternary operator), b-and, b-xor, b-or, or, and, ==, !=, <=>, <, >, >=, <=, in, matches, starts with, ends with, has every, has some, .., +, -, ~, *, /, //, %, is (tests), **, ??, | (filters), [], and .:

演算子の優先順位は次のとおりです。優先順位の最も低い演算子が最初にリストされています: ?: (三項演算子)、b-and、b-xor、b-or,or、and、==、!=、、、>=、
1
2
3
4
5
6
7
{% set greeting = 'Hello ' %}
{% set name = 'Fabien' %}

{{ greeting ~ name|lower }}   {# Hello fabien #}

{# use parenthesis to change precedence #}
{{ (greeting ~ name)|lower }} {# hello fabien #}

Literals

The simplest form of expressions are literals. Literals are representations for PHP types such as strings, numbers, and arrays. The following literals exist:

式の最も単純な形式はリテラルです。リテラルは、文字列、数値、配列などの PHP 型の表現です。次のリテラルが存在します。
  • "Hello World": Everything between two double or single quotes is a string. They are useful whenever you need a string in the template (for example as arguments to function calls, filters or just to extend or include a template). A string can contain a delimiter if it is preceded by a backslash (\) -- like in 'It\'s good'. If the string contains a backslash (e.g. 'c:\Program Files') escape it by doubling it (e.g. 'c:\\Program Files').
    "Hello World": 2 つの二重引用符または単一引用符の間はすべて astring です。これらは、テンプレートに文字列が必要な場合に便利です (たとえば、関数呼び出し、フィルターへの引数として、または単にテンプレートを拡張または含めるため)。 'It\'s good' のように、バックスラッシュ (\) が前にある場合、文字列に区切り文字を含めることができます。文字列にバックスラッシュが含まれている場合 (例: 'c:\Program Files')、二重にしてエスケープします (例: 'c:\\Program Files')。
  • 42 / 42.23: Integers and floating point numbers are created by writing the number down. If a dot is present the number is a float, otherwise an integer.
    42 / 42.23: 整数と浮動小数点数は、数値を書き留めることによって作成されます。ドットが存在する場合、数値は float であり、そうでない場合は整数です。
  • ["foo", "bar"]: Arrays are defined by a sequence of expressions separated by a comma (,) and wrapped with squared brackets ([]).
    ["foo", "bar"]: 配列は、コンマ (,) で区切られ、角かっこ ([]) で囲まれた一連の式によって定義されます。
  • {"foo": "bar"}: Hashes are defined by a list of keys and values separated by a comma (,) and wrapped with curly braces ({}):

    {"foo": "bar"}: ハッシュは、コンマ (,) で区切られ、中かっこ ({}) で囲まれたキーと値のリストによって定義されます。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    {# keys as string #}
    { 'foo': 'foo', 'bar': 'bar' }
    
    {# keys as names (equivalent to the previous hash) #}
    { foo: 'foo', bar: 'bar' }
    
    {# keys as integer #}
    { 2: 'foo', 4: 'bar' }
    
    {# keys can be omitted if it is the same as the variable name #}
    { foo }
    {# is equivalent to the following #}
    { 'foo': foo }
    
    {# keys as expressions (the expression must be enclosed into parentheses) #}
    {% set foo = 'foo' %}
    { (foo): 'foo', (1 + 1): 'bar', (foo ~ 'b'): 'baz' }
  • true / false: true represents the true value, false represents the false value.
    true / false: true は真の値を表し、false は偽の値を表します。
  • null: null represents no specific value. This is the value returned when a variable does not exist. none is an alias for null.
    null: null は特定の値がないことを表します。これは、変数が存在しない場合に返される値です。 none は null のエイリアスです。

Arrays and hashes can be nested:

配列とハッシュは入れ子にすることができます:
1
{% set foo = [1, {"foo": "bar"}] %}

Tip

ヒント

Using double-quoted or single-quoted strings has no impact on performance but string interpolation is only supported in double-quoted strings.

二重引用符または一重引用符で囲まれた文字列を使用してもパフォーマンスには影響しませんが、文字列補間は二重引用符で囲まれた文字列でのみサポートされます。

Math

Twig allows you to do math in templates; the following operators are supported:

Twig を使用すると、テンプレートで計算を行うことができます。次の演算子がサポートされています。
  • +: Adds two numbers together (the operands are casted to numbers). {{ 1 + 1 }} is 2.
    +: 2 つの数値を加算します (オペランドは数値にキャストされます)。 {{1 + 1}} は 2 です。
  • -: Subtracts the second number from the first one. {{ 3 - 2 }} is 1.
    -: 最初の数値から 2 番目の数値を引きます。 {{ 3 - 2 }} は 1 です。
  • /: Divides two numbers. The returned value will be a floating point number. {{ 1 / 2 }} is {{ 0.5 }}.
    /: 2 つの数値を除算します。戻り値は浮動小数点数になります。 {{ 1 / 2 }} は {{ 0.5 }} です。
  • %: Calculates the remainder of an integer division. {{ 11 % 7 }} is 4.
    %: 整数除算の剰余を計算します。 {{ 11 % 7 }} は 4.
  • //: Divides two numbers and returns the floored integer result. {{ 20 // 7 }} is 2, {{ -20 // 7 }} is -3 (this is just syntactic sugar for the round filter).
    //: 2 つの数値を除算し、フロア型整数の結果を返します。 {{ 20// 7 }} は 2、{{ -20// 7 }} は -3 です (これはラウンド フィルターの単なる構文糖衣です)。
  • *: Multiplies the left operand with the right one. {{ 2 * 2 }} would return 4.
    *: 左オペランドと右オペランドを乗算します。 {{ 2 * 2 }} は 4 を返します。
  • **: Raises the left operand to the power of the right operand. {{ 2 ** 3 }} would return 8.
    **: 左オペランドを右オペランドで累乗します。 {{ 2 **3 }} は 8 を返します。

Logic

You can combine multiple expressions with the following operators:

複数の式を次の演算子と組み合わせることができます。
  • and: Returns true if the left and the right operands are both true.
    and: 左右のオペランドが両方とも true の場合に true を返します。
  • or: Returns true if the left or the right operand is true.
    or: 左または右のオペランドが true の場合に true を返します。
  • not: Negates a statement.
    not: ステートメントを否定します。
  • (expr): Groups an expression.
    (expr): 式をグループ化します。

Note

ノート

Twig also supports bitwise operators (b-and, b-xor, and b-or).

Twig はビット単位の演算子 (b-and、b-xor、および b-or) もサポートしています。

Note

ノート

Operators are case sensitive.

演算子は大文字と小文字が区別されます。

Comparisons

The following comparison operators are supported in any expression: ==, !=, <, >, >=, and <=.

次の比較演算子は、すべての式でサポートされています: ==、!=、、>=、および

Check if a string starts with or ends with another string:

文字列が別の文字列で開始または終了するかどうかを確認します。
1
2
3
4
5
{% if 'Fabien' starts with 'F' %}
{% endif %}

{% if 'Fabien' ends with 'n' %}
{% endif %}

Check that a string contains another string via the containment operator (see next section).

包含演算子を使用して、文字列に別の文字列が含まれていることを確認します (次のセクションを参照)。

Note

ノート

For complex string comparisons, the matches operator allows you to use regular expressions:

複雑な文字列比較では、matches 演算子を使用して正規表現を使用できます。
1
2
{% if phone matches '/^[\\d\\.]+$/' %}
{% endif %}

Check that a sequence or a mapping has every or has some of its elements return true using an arrow function. The arrow function receives the value of the sequence or mapping:

アロー関数を使用して、シーケンスまたはマッピングのすべての要素または一部の要素が true を返すことを確認します。アロー関数は、シーケンスまたはマッピングの値を受け取ります。
1
2
3
4
5
6
7
{% set sizes = [34, 36, 38, 40, 42] %}

{% set hasOnlyOver38 = sizes has every v => v > 38 %}
{# hasOnlyOver38 is false #}

{% set hasOver38 = sizes has some v => v > 38 %}
{# hasOver38 is true #}

Containment Operator

The in operator performs containment test. It returns true if the left operand is contained in the right:

in 演算子は包含テストを実行します。左オペランドが右オペランドに含まれている場合、true を返します。
1
2
3
4
5
{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

Tip

ヒント

You can use this filter to perform a containment test on strings, arrays, or objects implementing the Traversable interface.

このフィルターを使用して、Traversable インターフェースを実装する文字列、配列、またはオブジェクトに対して封じ込めテストを実行できます。

To perform a negative test, use the not in operator:

否定的なテストを実行するには、not in 演算子を使用します。
1
2
3
4
{% if 1 not in [1, 2, 3] %}

{# is equivalent to #}
{% if not (1 in [1, 2, 3]) %}

Test Operator

The is operator performs tests. Tests can be used to test a variable against a common expression. The right operand is name of the test:

is 演算子はテストを実行します。テストを使用して、一般的な式に対して変数をテストできます。右側のオペランドはテストの名前です:
1
2
3
{# find out if a variable is odd #}

{{ name is odd }}

Tests can accept arguments too:

テストは引数も受け入れることができます:
1
{% if post.status is constant('Post::PUBLISHED') %}

Tests can be negated by using the is not operator:

is not 演算子を使用して、テストを否定できます。
1
2
3
4
{% if post.status is not constant('Post::PUBLISHED') %}

{# is equivalent to #}
{% if not (post.status is constant('Post::PUBLISHED')) %}

Go to the tests page to learn more about the built-in tests.

組み込みテストの詳細については、テスト ページに移動してください。

Other Operators

The following operators don't fit into any of the other categories:

次の演算子は、他のどのカテゴリにも当てはまりません。
  • |: Applies a filter.
    |: フィルターを適用します。
  • ..: Creates a sequence based on the operand before and after the operator (this is syntactic sugar for the range function):

    ..: 演算子の前後のオペランドに基づいてシーケンスを作成します (これは range 関数のシンタックス シュガーです):
    1
    2
    3
    4
    {{ 1..5 }}
    
    {# equivalent to #}
    {{ range(1, 5) }}

    Note that you must use parentheses when combining it with the filter operator due to the operator precedence rules:

    演算子の優先順位規則により、フィルター演算子と組み合わせる場合は括弧を使用する必要があることに注意してください。
    1
    (1..5)|join(', ')
  • ~: Converts all operands into strings and concatenates them. {{ "Hello " ~ name ~ "!" }} would return (assuming name is 'John') Hello John!.
    ~: すべてのオペランドを文字列に変換して連結します。 {{「こんにちは」~名前~「!」 }} は (名前が 'John' であると仮定して) HelloJohn! を返します。
  • ., []: Gets an attribute of a variable.
    ., []: 変数の属性を取得します。
  • ?:: The ternary operator:

    ?:: 三項演算子:
    1
    2
    3
    {{ foo ? 'yes' : 'no' }}
    {{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
    {{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
  • ??: The null-coalescing operator:

    ??: null 合体演算子:
    1
    2
    {# returns the value of foo if it is defined and not null, 'no' otherwise #}
    {{ foo ?? 'no' }}

String Interpolation

String interpolation (#{expression}) allows any valid expression to appear within a double-quoted string. The result of evaluating that expression is inserted into the string:

文字列補間 (#{expression}) を使用すると、二重引用符で囲まれた文字列内に有効な式を表示できます。その式を評価した結果が文字列に挿入されます。
1
2
{{ "foo #{bar} baz" }}
{{ "foo #{1 + 2} baz" }}

Whitespace Control

The first newline after a template tag is removed automatically (like in PHP). Whitespace is not further modified by the template engine, so each whitespace (spaces, tabs, newlines etc.) is returned unchanged.

テンプレート タグの後の最初の改行は (PHP のように) 自動的に削除されます。空白はテンプレート エンジンによってそれ以上変更されないため、各空白 (スペース、タブ、改行など) は変更されずに返されます。

You can also control whitespace on a per tag level. By using the whitespace control modifiers on your tags, you can trim leading and or trailing whitespace.

タグレベルごとに空白を制御することもできます。タグで whitespacecontrol 修飾子を使用すると、先頭または末尾の空白を削除できます。

Twig supports two modifiers:

Twig は 2 つの修飾子をサポートします。
  • Whitespace trimming via the - modifier: Removes all whitespace (including newlines);
    - 修飾子による空白のトリミング: すべての空白 (改行を含む) を削除します。
  • Line whitespace trimming via the ~ modifier: Removes all whitespace (excluding newlines). Using this modifier on the right disables the default removal of the first newline inherited from PHP.
    ~ 修飾子による行の空白のトリミング: すべての空白 (改行を除く) を削除します。この修飾子を右側で使用すると、PHP から継承された最初の改行のデフォルトの削除が無効になります。

The modifiers can be used on either side of the tags like in {%- or -%} and they consume all whitespace for that side of the tag. It is possible to use the modifiers on one side of a tag or on both sides:

修飾子は、{%- または -%} のようにタグの両側で使用でき、タグのその側のすべての空白を消費します。タグの片側または両側で修飾子を使用することができます。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{% set value = 'no spaces' %}
{#- No leading/trailing whitespace -#}
{%- if true -%}
    {{- value -}}
{%- endif -%}
{# output 'no spaces' #}

<li>
    {{ value }}    </li>
{# outputs '<li>\n    no spaces    </li>' #}

<li>
    {{- value }}    </li>
{# outputs '<li>no spaces    </li>' #}

<li>
    {{~ value }}    </li>
{# outputs '<li>\nno spaces    </li>' #}

Tip

ヒント

In addition to the whitespace modifiers, Twig also has a spaceless filter that removes whitespace between HTML tags:

空白修飾子に加えて、Twig には HTML タグ間の空白を削除する spaceless フィルターもあります。
1
2
3
4
5
6
7
{% apply spaceless %}
    <div>
        <strong>foo bar</strong>
    </div>
{% endapply %}

{# output will be <div><strong>foo bar</strong></div> #}

Extensions

Twig can be extended. If you want to create your own extensions, read the Creating an Extension chapter.

小枝は伸ばすことができます。独自の拡張機能を作成する場合は、拡張機能の作成の章をお読みください。