How to Inject Variables Automatically into all Templates

Twig allows you to automatically inject one or more variables into all templates. These global variables are defined in the twig.globals option inside the main Twig configuration file:

Twig では、すべてのテンプレートに 1 つ以上の変数を自動的に挿入できます。これらのグローバル変数は、メインの Twig 構成ファイル内の twig.globals オプションで定義されます。
  • YAML
    YAML
  • XML
    XML
  • PHP
    PHP
1
2
3
4
5
# config/packages/twig.yaml
twig:
    # ...
    globals:
        ga_tracking: 'UA-xxxxx-x'

Now, the variable ga_tracking is available in all Twig templates, so you can use it without having to pass it explicitly from the controller or service that renders the template:

現在、変数 ga_tracking はすべての Twig テンプレートで使用できるため、テンプレートをレンダリングするコントローラーまたはサービスから明示的に渡す必要なく使用できます。
1
<p>The Google tracking code is: {{ ga_tracking }}</p>

Referencing Services

In addition to static values, Twig global variables can also reference services from the service container. The main drawback is that these services are not loaded lazily. In other words, as soon as Twig is loaded, your service is instantiated, even if you never use that global variable.

静的な値に加えて、Twig グローバル変数は、サービス コンテナーからサービスを参照することもできます。主な欠点は、これらのサービスが遅延ロードされないことです。つまり、Twig がロードされるとすぐに、そのグローバル変数をまったく使用しなくても、サービスがインスタンス化されます。

To define a service as a global Twig variable, prefix the service ID string with the @ character, which is the usual syntax to refer to services in container parameters:

サービスをグローバル Twig 変数として定義するには、サービス ID 文字列の前に @ 文字を付けます。これは、コンテナー パラメーターでサービスを参照する通常の構文です。
  • YAML
    YAML
  • XML
    XML
  • PHP
    PHP
1
2
3
4
5
6
# config/packages/twig.yaml
twig:
    # ...
    globals:
        # the value is the service's id
        uuid: '@App\Generator\UuidGenerator'

Now you can use the uuid variable in any Twig template to access to the UuidGenerator service:

Twig テンプレートで uuid 変数を使用して、UuidGenerator サービスにアクセスできるようになりました。
1
UUID: {{ uuid.generate }}