Twig for Developers

This chapter describes the API to Twig and not the template language. It will be most useful as reference to those implementing the template interface to the application and not those who are creating Twig templates.

この章では、テンプレート言語ではなく、Twig への API について説明します。これは、Twig テンプレートを作成している人ではなく、アプリケーションへのテンプレート インターフェイスを実装している人への参照として最も役立ちます。

Basics

Twig uses a central object called the environment (of class \Twig\Environment). Instances of this class are used to store the configuration and extensions, and are used to load templates.

Twig は、(class\Twig\Environment の) 環境と呼ばれる中心的なオブジェクトを使用します。このクラスのインスタンスは、構成と拡張機能を格納するために使用され、テンプレートをロードするために使用されます。

Most applications create one \Twig\Environment object on application initialization and use that to load templates. In some cases, it might be useful to have multiple environments side by side, with different configurations.

ほとんどのアプリケーションは、アプリケーションの初期化時に 1 つの \Twig\Environment オブジェクトを作成し、それを使用してテンプレートを読み込みます。場合によっては、構成の異なる複数の環境を並べて配置すると便利な場合があります。

The typical way to configure Twig to load templates for an application looks roughly like this:

アプリケーションのテンプレートをロードするように Twig を構成する一般的な方法は、おおよそ次のようになります。
1
2
3
4
5
6
require_once '/path/to/vendor/autoload.php';

$loader = new \Twig\Loader\FilesystemLoader('/path/to/templates');
$twig = new \Twig\Environment($loader, [
    'cache' => '/path/to/compilation_cache',
]);

This creates a template environment with a default configuration and a loader that looks up templates in the /path/to/templates/ directory. Different loaders are available and you can also write your own if you want to load templates from a database or other resources.

これにより、デフォルト構成と /path/to/templates/ ディレクトリでテンプレートを検索するローダーを備えたテンプレート環境が作成されます。さまざまなローダーが利用可能で、データベースやその他のリソースからテンプレートをロードする場合は、独自のローダーを作成することもできます。

Note

ノート

Notice that the second argument of the environment is an array of options. The cache option is a compilation cache directory, where Twig caches the compiled templates to avoid the parsing phase for sub-sequent requests. It is very different from the cache you might want to add for the evaluated templates. For such a need, you can use any available PHP cache library.

環境の 2 番目の引数はオプションの配列であることに注意してください。キャッシュ オプションはコンパイル キャッシュ ディレクトリであり、Twig はコンパイルされたテンプレートをキャッシュして、後続のリクエストの解析フェーズを回避します。これは、評価されたテンプレートに追加するキャッシュとは大きく異なります。このような必要がある場合は、利用可能な任意の PHPcache ライブラリを使用できます。

Rendering Templates

To load a template from a Twig environment, call the load() method which returns a \Twig\TemplateWrapper instance:

Twig 環境からテンプレートをロードするには、\Twig\TemplateWrapper インスタンスを返す load() メソッドを呼び出します。
1
$template = $twig->load('index.html');

To render the template with some variables, call the render() method:

テンプレートをいくつかの変数でレンダリングするには、render() メソッドを呼び出します。
1
echo $template->render(['the' => 'variables', 'go' => 'here']);

Note

ノート

The display() method is a shortcut to output the rendered template.

display() メソッドは、レンダリングされたテンプレートを出力するためのショートカットです。

You can also load and render the template in one fell swoop:

テンプレートを一気に読み込んでレンダリングすることもできます。
1
echo $twig->render('index.html', ['the' => 'variables', 'go' => 'here']);

If a template defines blocks, they can be rendered individually via the renderBlock() call:

テンプレートがブロックを定義する場合、renderBlock() 呼び出しを介して個別にレンダリングできます。
1
echo $template->renderBlock('block_name', ['the' => 'variables', 'go' => 'here']);

Environment Options

When creating a new \Twig\Environment instance, you can pass an array of options as the constructor second argument:

新しい \Twig\Environment インスタンスを作成するとき、オプションの配列をコンストラクターの 2 番目の引数として渡すことができます。
1
$twig = new \Twig\Environment($loader, ['debug' => true]);

The following options are available:

次のオプションを使用できます。
  • debug boolean

    デバッグブール値

    When set to true, the generated templates have a __toString() method that you can use to display the generated nodes (default to false).

    true に設定すると、生成されたテンプレートには、生成されたノードを表示するために使用できる __toString() メソッドが含まれます (デフォルトは false)。
  • charset string (defaults to utf-8)

    文字セット文字列 (デフォルトは utf-8)

    The charset used by the templates.

    テンプレートで使用される文字セット。
  • cache string or false

    キャッシュ文字列または false

    An absolute path where to store the compiled templates, or false to disable caching (which is the default).

    コンパイルされたテンプレートを保存する絶対パス。キャッシュを無効にする場合は false (デフォルト)。
  • auto_reload boolean

    auto_reload ブール値

    When developing with Twig, it's useful to recompile the template whenever the source code changes. If you don't provide a value for the auto_reload option, it will be determined automatically based on the debug value.

    Twig で開発する場合、ソース コードが変更されるたびにテンプレートを再コンパイルすると便利です。 auto_reload オプションの値を指定しない場合、debug 値に基づいて自動的に決定されます。
  • strict_variables boolean

    strict_variables ブール値

    If set to false, Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true, Twig throws an exception instead (default to false).

    false に設定すると、Twig は無効な変数 (存在しない変数や属性/メソッド) を黙って無視し、null 値に置き換えます。 true に設定すると、Twig は代わりに例外をスローします (デフォルトは false)。
  • autoescape string

    自動エスケープ文字列

    Sets the default auto-escaping strategy (name, html, js, css, url, html_attr, or a PHP callback that takes the template "filename" and returns the escaping strategy to use -- the callback cannot be a function name to avoid collision with built-in escaping strategies); set it to false to disable auto-escaping. The name escaping strategy determines the escaping strategy to use for a template based on the template filename extension (this strategy does not incur any overhead at runtime as auto-escaping is done at compilation time.)

    デフォルトの自動エスケープ戦略 (name、html、js、css、url、html_attr、またはテンプレート「ファイル名」を受け取り、使用するエスケープ戦略を返す PHP コールバックを設定します。組み込みのエスケープ戦略);自動エスケープを無効にするには、false に設定します。名前エスケープ戦略は、テンプレートのファイル名拡張子に基づいて、テンプレートに使用するエスケープ戦略を決定します (自動エスケープはコンパイル時に行われるため、この戦略では実行時にオーバーヘッドが発生しません)。
  • optimizations integer

    最適化整数

    A flag that indicates which optimizations to apply (default to -1 -- all optimizations are enabled; set it to 0 to disable).

    どの最適化を適用するかを示すフラグ (デフォルトは -1 -- すべての最適化が有効、無効にするには 0 に設定)。

Loaders

Loaders are responsible for loading templates from a resource such as the file system.

ローダーは、ファイルシステムなどのリソースからテンプレートをロードする役割を果たします。

Compilation Cache

All template loaders can cache the compiled templates on the filesystem for future reuse. It speeds up Twig a lot as templates are only compiled once.

すべてのテンプレート ローダーは、将来の再利用のためにコンパイル済みのテンプレートをファイル システムにキャッシュできます。テンプレートは一度しかコンパイルされないため、Twig の速度が大幅に向上します。

Built-in Loaders

Here is a list of the built-in loaders:

組み込みローダーのリストは次のとおりです。

\Twig\Loader\FilesystemLoader

\Twig\Loader\FilesystemLoader loads templates from the file system. This loader can find templates in folders on the file system and is the preferred way to load them:

\Twig\Loader\FilesystemLoader は、ファイル システムからテンプレートをロードします。このローダーは、ファイル システム上のフォルダー内のテンプレートを見つけることができ、それらをロードするための推奨される方法です。
1
$loader = new \Twig\Loader\FilesystemLoader($templateDir);

It can also look for templates in an array of directories:

ディレクトリの配列でテンプレートを探すこともできます。
1
$loader = new \Twig\Loader\FilesystemLoader([$templateDir1, $templateDir2]);

With such a configuration, Twig will first look for templates in $templateDir1 and if they do not exist, it will fallback to look for them in the $templateDir2.

このような構成では、Twig は最初に $templateDir1 でテンプレートを検索し、それらが存在しない場合は、フォールバックして $templateDir2 でテンプレートを検索します。

You can add or prepend paths via the addPath() and prependPath() methods:

addPath() および prependPath() メソッドを使用して、パスを追加または先頭に追加できます。
1
2
$loader->addPath($templateDir3);
$loader->prependPath($templateDir4);

The filesystem loader also supports namespaced templates. This allows to group your templates under different namespaces which have their own template paths.

ファイルシステム ローダーは、名前空間付きのテンプレートもサポートしています。これにより、独自のテンプレート パスを持つさまざまな名前空間でテンプレートをグループ化できます。

When using the setPaths(), addPath(), and prependPath() methods, specify the namespace as the second argument (when not specified, these methods act on the "main" namespace):

setPaths()、addPath()、および prependPath() メソッドを使用する場合は、名前空間を 2 番目の引数として指定します (指定しない場合、これらのメソッドは「メイン」名前空間で機能します)。
1
$loader->addPath($templateDir, 'admin');

Namespaced templates can be accessed via the special @namespace_name/template_path notation:

名前空間テンプレートには、special@namespace_name/template_path 表記を介してアクセスできます。
1
$twig->render('@admin/index.html', []);

\Twig\Loader\FilesystemLoader supports absolute and relative paths. Using relative paths is preferred as it makes the cache keys independent of the project root directory (for instance, it allows warming the cache from a build server where the directory might be different from the one used on production servers):

\Twig\Loader\FilesystemLoader は、絶対パスと相対パスをサポートしています。プロジェクトのルート ディレクトリからキャッシュ キーを独立させるため、相対パスを使用することをお勧めします (たとえば、運用サーバーで使用されているディレクトリとは異なる可能性があるビルド サーバーからキャッシュをウォーミングできます)。
1
$loader = new \Twig\Loader\FilesystemLoader('templates', getcwd().'/..');

Note

ノート

When not passing the root path as a second argument, Twig uses getcwd() for relative paths.

2 番目の引数としてルート パスを渡さない場合、Twig は相対パスに getcwd() を使用します。

\Twig\Loader\ArrayLoader

\Twig\Loader\ArrayLoader loads a template from a PHP array. It is passed an array of strings bound to template names:

\Twig\Loader\ArrayLoader は PHP 配列からテンプレートをロードします。テンプレート名にバインドされた文字列の配列が渡されます。
1
2
3
4
5
6
$loader = new \Twig\Loader\ArrayLoader([
    'index.html' => 'Hello {{ name }}!',
]);
$twig = new \Twig\Environment($loader);

echo $twig->render('index.html', ['name' => 'Fabien']);

This loader is very useful for unit testing. It can also be used for small projects where storing all templates in a single PHP file might make sense.

このローダーは、単体テストに非常に役立ちます。また、すべてのテンプレートを 1 つの PHP ファイルに格納することが理にかなっている小さなプロジェクトにも使用できます。

Tip

ヒント

When using the Array loader with a cache mechanism, you should know that a new cache key is generated each time a template content "changes" (the cache key being the source code of the template). If you don't want to see your cache grows out of control, you need to take care of clearing the old cache file by yourself.

キャッシュ メカニズムで配列ローダーを使用する場合、テンプレート コンテンツが「変更」されるたびに新しいキャッシュ キーが生成されることを知っておく必要があります (キャッシュ キーはテンプレートのソース コードです)。キャッシュが制御不能になるのを見たくない場合は、古いキャッシュ ファイルを自分でクリアする必要があります。

\Twig\Loader\ChainLoader

\Twig\Loader\ChainLoader delegates the loading of templates to other loaders:

\Twig\Loader\ChainLoader は、テンプレートの読み込みを他のローダーに委任します。
1
2
3
4
5
6
7
8
9
10
11
$loader1 = new \Twig\Loader\ArrayLoader([
    'base.html' => '{% block content %}{% endblock %}',
]);
$loader2 = new \Twig\Loader\ArrayLoader([
    'index.html' => '{% extends "base.html" %}{% block content %}Hello {{ name }}{% endblock %}',
    'base.html'  => 'Will never be loaded',
]);

$loader = new \Twig\Loader\ChainLoader([$loader1, $loader2]);

$twig = new \Twig\Environment($loader);

When looking for a template, Twig tries each loader in turn and returns as soon as the template is found. When rendering the index.html template from the above example, Twig will load it with $loader2 but the base.html template will be loaded from $loader1.

テンプレートを探すとき、Twig は各ローダーを順番に試し、テンプレートが見つかるとすぐに戻ります。上記の例から index.html テンプレートをレンダリングすると、Twig は $loader2 でそれをロードしますが、base.html テンプレートは $loader1 からロードされます。

Note

ノート

You can also add loaders via the addLoader() method.

addLoader() メソッドを介してローダーを追加することもできます。

Create your own Loader

All loaders implement the \Twig\Loader\LoaderInterface:

すべてのローダーは \Twig\Loader\LoaderInterface を実装します:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
interface \Twig\Loader\LoaderInterface
{
    /**
     * Returns the source context for a given template logical name.
     *
     * @param string $name The template logical name
     *
     * @return \Twig\Source
     *
     * @throws \Twig\Error\LoaderError When $name is not found
     */
    public function getSourceContext($name);

    /**
     * Gets the cache key to use for the cache for a given template name.
     *
     * @param string $name The name of the template to load
     *
     * @return string The cache key
     *
     * @throws \Twig\Error\LoaderError When $name is not found
     */
    public function getCacheKey($name);

    /**
     * Returns true if the template is still fresh.
     *
     * @param string    $name The template name
     * @param timestamp $time The last modification time of the cached template
     *
     * @return bool    true if the template is fresh, false otherwise
     *
     * @throws \Twig\Error\LoaderError When $name is not found
     */
    public function isFresh($name, $time);

    /**
     * Check if we have the source code of a template, given its name.
     *
     * @param string $name The name of the template to check if we can load
     *
     * @return bool    If the template source code is handled by this loader or not
     */
    public function exists($name);
}

The isFresh() method must return true if the current cached template is still fresh, given the last modification time, or false otherwise.

isFresh() メソッドは、現在のキャッシュされたテンプレートがまだ新しい場合は true を返す必要があり、最終変更時刻が指定されている場合、または false を返す必要があります。

The getSourceContext() method must return an instance of \Twig\Source.

getSourceContext() メソッドは \Twig\Source のインスタンスを返さなければなりません。

Using Extensions

Twig extensions are packages that add new features to Twig. Register an extension via the addExtension() method:

Twig 拡張機能は、Twig に新しい機能を追加するパッケージです。 addExtension() メソッドを介して拡張機能を登録します。
1
$twig->addExtension(new \Twig\Extension\SandboxExtension());

Twig comes bundled with the following extensions:

Twig には、次の拡張機能がバンドルされています。
  • TwigExtensionCoreExtension: Defines all the core features of Twig.
    TwigExtensionCoreExtension: Twig のすべてのコア機能を定義します。
  • TwigExtensionDebugExtension: Defines the dump function to help debug template variables.
    TwigExtensionDebugExtension: テンプレート変数のデバッグに役立つダンプ関数を定義します。
  • TwigExtensionEscaperExtension: Adds automatic output-escaping and the possibility to escape/unescape blocks of code.
    TwigExtensionEscaperExtension: 自動出力エスケープと、コード ブロックのエスケープ/エスケープ解除の可能性を追加します。
  • TwigExtensionSandboxExtension: Adds a sandbox mode to the default Twig environment, making it safe to evaluate untrusted code.
    TwigExtensionSandboxExtension: デフォルトの Twigenvironment にサンドボックス モードを追加し、信頼されていないコードを安全に評価できるようにします。
  • TwigExtensionProfilerExtension: Enables the built-in Twig profiler.
    TwigExtensionProfilerExtension: 組み込みの Twig プロファイラーを有効にします。
  • TwigExtensionOptimizerExtension: Optimizes the node tree before compilation.
    TwigExtensionOptimizerExtension: コンパイル前にノード ツリーを最適化します。
  • TwigExtensionStringLoaderExtension: Defines the template_from_string
    function to allow loading templates from string in a template.
    テンプレート内の文字列からテンプレートをロードできるようにする関数。
    TwigExtensionStringLoaderExtension: テンプレート内の文字列からテンプレートをロードできるようにする template_from_string 関数を定義します。

The Core, Escaper, and Optimizer extensions are registered by default.

Core、Escaper、および Optimizer 拡張機能は、デフォルトで登録されています。

Built-in Extensions

This section describes the features added by the built-in extensions.

このセクションでは、組み込みの拡張機能によって追加された機能について説明します。

Tip

ヒント

Read the chapter about extending Twig to learn how to create your own extensions.

Twig の拡張に関する章を読んで、独自の拡張機能を作成する方法を学んでください。

Core Extension

The core extension defines all the core features of Twig:

core 拡張機能は、Twig のすべてのコア機能を定義します。

Escaper Extension

The escaper extension adds automatic output escaping to Twig. It defines a tag, autoescape, and a filter, raw.

エスケーパー拡張機能は、自動出力エスケープを Twig に追加します。これは、atag、autoescape、およびフィルター raw を定義します。

When creating the escaper extension, you can switch on or off the global output escaping strategy:

エスケーパー拡張機能を作成するときに、globaloutput エスケープ戦略をオンまたはオフに切り替えることができます。
1
2
$escaper = new \Twig\Extension\EscaperExtension('html');
$twig->addExtension($escaper);

If set to html, all variables in templates are escaped (using the html escaping strategy), except those using the raw filter:

html に設定すると、生のフィルターを使用するものを除いて、テンプレート内のすべての変数が (htmlescaping 戦略を使用して) エスケープされます。
1
{{ article.to_html|raw }}

You can also change the escaping mode locally by using the autoescape tag:

autoescape タグを使用して、ローカルでエスケープ モードを変更することもできます。
1
2
3
4
5
{% autoescape 'html' %}
    {{ var }}
    {{ var|raw }}      {# var won't be escaped #}
    {{ var|escape }}   {# var won't be double-escaped #}
{% endautoescape %}

Warning

警告

The autoescape tag has no effect on included files.

autoescape タグは、インクルード ファイルには影響しません。

The escaping rules are implemented as follows:

エスケープ規則は次のように実装されます。
  • Literals (integers, booleans, arrays, ...) used in the template directly as variables or filter arguments are never automatically escaped:

    テンプレートで変数またはフィルター引数として直接使用されるリテラル (整数、ブール値、配列など) は、自動的にエスケープされることはありません。
    1
    2
    3
    4
    {{ "Twig<br/>" }} {# won't be escaped #}
    
    {% set text = "Twig<br/>" %}
    {{ text }} {# will be escaped #}
  • Expressions which the result is a literal or a variable marked safe are never automatically escaped:

    結果がリテラルまたは safe とマークされた変数である式は、自動的にエスケープされることはありません。
    1
    2
    3
    4
    5
    6
    7
    8
    {{ foo ? "Twig<br/>" : "<br/>Twig" }} {# won't be escaped #}
    
    {% set text = "Twig<br/>" %}
    {{ true ? text : "<br/>Twig" }} {# will be escaped #}
    {{ false ? text : "<br/>Twig" }} {# won't be escaped #}
    
    {% set text = "Twig<br/>" %}
    {{ foo ? text|raw : "<br/>Twig" }} {# won't be escaped #}
  • Objects with a __toString method are converted to strings and escaped. You can mark some classes and/or interfaces as being safe for some strategies via EscaperExtension::addSafeClass():

    __toString メソッドを持つオブジェクトは文字列に変換され、エスケープされます。 EscaperExtension::addSafeClass() を使用して、いくつかのクラスやインターフェースをいくつかの戦略に対して安全であるとマークすることができます。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // mark object of class Foo as safe for the HTML strategy
    $escaper->addSafeClass('Foo', ['html']);
    
    // mark object of interface Foo as safe for the HTML strategy
    $escaper->addSafeClass('FooInterface', ['html']);
    
    // mark object of class Foo as safe for the HTML and JS strategies
    $escaper->addSafeClass('Foo', ['html', 'js']);
    
    // mark object of class Foo as safe for all strategies
    $escaper->addSafeClass('Foo', ['all']);
  • Escaping is applied before printing, after any other filter is applied:

    他のフィルタが適用された後、印刷前にエスケープが適用されます。
    1
    {{ var|upper }} {# is equivalent to {{ var|upper|escape }} #}
  • The `raw` filter should only be used at the end of the filter chain:

    `raw` フィルターは、フィルター チェーンの最後でのみ使用する必要があります。
    1
    2
    3
    {{ var|raw|upper }} {# will be escaped #}
    
    {{ var|upper|raw }} {# won't be escaped #}
  • Automatic escaping is not applied if the last filter in the chain is marked safe for the current context (e.g. html or js). escape and escape('html') are marked safe for HTML, escape('js') is marked safe for JavaScript, raw is marked safe for everything.

    チェーンの最後のフィルターが現在のコンテキスト (html や js など) に対して安全であるとマークされている場合、自動エスケープは適用されません。 escape および escape('html') は HTML に対して安全であるとマークされ、escape('js') は JavaScript に対して安全であるとマークされ、raw はすべてに対して安全であるとマークされています。
    1
    2
    3
    4
    5
    {% autoescape 'js' %}
        {{ var|escape('html') }} {# will be escaped for HTML and JavaScript #}
        {{ var }} {# will be escaped for JavaScript #}
        {{ var|escape('js') }} {# won't be double-escaped #}
    {% endautoescape %}

Note

ノート

Note that autoescaping has some limitations as escaping is applied on expressions after evaluation. For instance, when working with concatenation, {{ foo|raw ~ bar }} won't give the expected result as escaping is applied on the result of the concatenation, not on the individual variables (so, the raw filter won't have any effect here).

エスケープは評価後に式に適用されるため、自動エスケープにはいくつかの制限があることに注意してください。たとえば、連結を使用する場合、 {{ foo|raw ~ bar }} は、個々の変数ではなく、連結の結果にエスケープが適用されるため、期待される結果を提供しません (したがって、生のフィルターはここでは何の効果もありません)。 )。

Sandbox Extension

The sandbox extension can be used to evaluate untrusted code. Access to unsafe attributes and methods is prohibited. The sandbox security is managed by a policy instance. By default, Twig comes with one policy class: \Twig\Sandbox\SecurityPolicy. This class allows you to white-list some tags, filters, properties, and methods:

サンドボックス拡張機能を使用して、信頼されていないコードを評価できます。安全でない属性およびメソッドへのアクセスは禁止されています。サンドボックス セキュリティは、ポリシー インスタンスによって管理されます。デフォルトでは、Twig には 1 つのポリシー クラス (\Twig\Sandbox\SecurityPolicy) が付属しています。このクラスを使用すると、いくつかのタグ、フィルター、プロパティ、およびメソッドをホワイトリストに登録できます。
1
2
3
4
5
6
7
8
9
10
$tags = ['if'];
$filters = ['upper'];
$methods = [
    'Article' => ['getTitle', 'getBody'],
];
$properties = [
    'Article' => ['title', 'body'],
];
$functions = ['range'];
$policy = new \Twig\Sandbox\SecurityPolicy($tags, $filters, $methods, $properties, $functions);

With the previous configuration, the security policy will only allow usage of the if tag, and the upper filter. Moreover, the templates will only be able to call the getTitle() and getBody() methods on Article objects, and the title and body public properties. Everything else won't be allowed and will generate a \Twig\Sandbox\SecurityError exception.

以前の構成では、セキュリティ ポリシーは if タグと上位フィルターの使用のみを許可します。さらに、テンプレートは Article オブジェクトの getTitle() メソッドと getBody() メソッド、および title と body パブリック プロパティのみを呼び出すことができます。それ以外はすべて許可されず、\Twig\Sandbox\SecurityError 例外が生成されます。

The policy object is the first argument of the sandbox constructor:

ポリシー オブジェクトは、サンドボックス コンストラクターの最初の引数です。
1
2
$sandbox = new \Twig\Extension\SandboxExtension($policy);
$twig->addExtension($sandbox);

By default, the sandbox mode is disabled and should be enabled when including untrusted template code by using the sandbox tag:

デフォルトでは、サンドボックス モードは無効になっており、サンドボックス タグを使用して信頼されていないテンプレート コードを含める場合は有効にする必要があります。
1
2
3
{% sandbox %}
    {% include 'user.html' %}
{% endsandbox %}

You can sandbox all templates by passing true as the second argument of the extension constructor:

拡張コンストラクターの 2 番目の引数として true を渡すことで、すべてのテンプレートをサンドボックス化できます。
1
$sandbox = new \Twig\Extension\SandboxExtension($policy, true);

Profiler Extension

The profiler extension enables a profiler for Twig templates; it should only be used on your development machines as it adds some overhead:

プロファイラー拡張機能は、Twig テンプレートのプロファイラーを有効にします。オーバーヘッドが追加されるため、開発マシンでのみ使用する必要があります。
1
2
3
4
5
$profile = new \Twig\Profiler\Profile();
$twig->addExtension(new \Twig\Extension\ProfilerExtension($profile));

$dumper = new \Twig\Profiler\Dumper\TextDumper();
echo $dumper->dump($profile);

A profile contains information about time and memory consumption for template, block, and macro executions.

プロファイルには、テンプレート、ブロック、およびマクロの実行にかかる時間とメモリ消費に関する情報が含まれています。

You can also dump the data in a Blackfire.io compatible format:

Blackfire.io と互換性のある形式でデータをダンプすることもできます。
1
2
$dumper = new \Twig\Profiler\Dumper\BlackfireDumper();
file_put_contents('/path/to/profile.prof', $dumper->dump($profile));

Upload the profile to visualize it (create a free account first):

プロファイルをアップロードして視覚化します (最初に無料のアカウントを作成します):
1
blackfire --slot=7 upload /path/to/profile.prof

Optimizer Extension

The optimizer extension optimizes the node tree before compilation:

最適化拡張機能は、コンパイル前にノード ツリーを最適化します。
1
$twig->addExtension(new \Twig\Extension\OptimizerExtension());

By default, all optimizations are turned on. You can select the ones you want to enable by passing them to the constructor:

デフォルトでは、すべての最適化がオンになっています。コンストラクターに渡すことで、有効にしたいものを選択できます。
1
2
3
$optimizer = new \Twig\Extension\OptimizerExtension(\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR);

$twig->addExtension($optimizer);

Twig supports the following optimizations:

Twig は次の最適化をサポートしています。
  • \Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_ALL, enables all optimizations (this is the default value).
    \Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_ALL、すべての最適化を有効にします (これはデフォルト値です)。
  • \Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_NONE, disables all optimizations. This reduces the compilation time, but it can increase the execution time and the consumed memory.
    \Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_NONE は、すべての最適化を無効にします。これにより、コンパイル時間が短縮されますが、実行時間と消費メモリが増加する可能性があります。
  • \Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR, optimizes the for tag by removing the loop variable creation whenever possible.
    \Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR は、可能な限りループ変数の作成を削除して for タグを最適化します。
  • \Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_RAW_FILTER, removes the raw filter whenever possible.
    \Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_RAW_FILTER は、可能な限り rawfilter を削除します。
  • \Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS, simplifies the creation and access of variables in the compiled templates whenever possible.
    \Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS は、コンパイルされたテンプレートでの変数の作成とアクセスを可能な限り簡素化します。

Exceptions

Twig can throw exceptions:

Twig は例外をスローできます。
  • \Twig\Error\Error: The base exception for all errors.
    \Twig\Error\Error: すべてのエラーの基本例外。
  • \Twig\Error\SyntaxError: Thrown to tell the user that there is a problem with the template syntax.
    \Twig\Error\SyntaxError: テンプレートの構文に問題があることをユーザーに伝えるためにスローされます。
  • \Twig\Error\RuntimeError: Thrown when an error occurs at runtime (when a filter does not exist for instance).
    \Twig\Error\RuntimeError: 実行時にエラーが発生した場合 (たとえば、フィルターが存在しない場合) にスローされます。
  • \Twig\Error\LoaderError: Thrown when an error occurs during template loading.
    \Twig\Error\LoaderError: テンプレートの読み込み中にエラーが発生した場合にスローされます。
  • \Twig\Sandbox\SecurityError: Thrown when an unallowed tag, filter, or method is called in a sandboxed template.
    \Twig\Sandbox\SecurityError: 許可されていないタグ、フィルター、またはメソッドがサンドボックス化されたテンプレートで呼び出されたときにスローされます。