template_from_string

The template_from_string function loads a template from a string:

template_from_string 関数は、文字列からテンプレートをロードします。
1
2
{{ include(template_from_string("Hello {{ name }}")) }}
{{ include(template_from_string(page.template)) }}

To ease debugging, you can also give the template a name that will be part of any related error message:

デバッグを容易にするために、関連するエラー メッセージの一部となる名前をテンプレートに付けることもできます。
1
{{ include(template_from_string(page.template, "template for page " ~ page.name)) }}

Note

ノート

The template_from_string function is not available by default.

デフォルトでは、template_from_string 関数は使用できません。

On Symfony projects, you need to load it in your services.yaml file:

Symfony プロジェクトでは、services.yaml ファイルにロードする必要があります。
1
2
services:
    Twig\Extension\StringLoaderExtension:

or services.php file:

または services.php ファイル:
1
$services->set(\Twig\Extension\StringLoaderExtension::class);

Otherwise, add the extension explicitly on the Twig environment:

それ以外の場合は、Twig 環境で拡張機能を明示的に追加します。
1
2
3
4
use Twig\Extension\StringLoaderExtension;

$twig = new \Twig\Environment(...);
$twig->addExtension(new StringLoaderExtension());

Note

ノート

Even if you will probably always use the template_from_string function with the include function, you can use it with any tag or function that takes a template as an argument (like the embed or extends tags).

インクルード関数で template_from_string 関数を常に使用する場合でも、テンプレートを引数として取る任意のタグまたは関数 (embed または extends タグなど) で使用できます。

Arguments

  • template: The template
    テンプレート: テンプレート
  • name: A name for the template
    name: テンプレートの名前