Twig for Developers翻译稿

  • 聚客宝
  • 2021-08-07 12:02:06

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模板的人,这将是最有用的参考。



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使用一个称为环境的中心对象(类\ 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.

大多数应用程序在应用程序初始化时创建一个\ Twig \ Environment对象,并使用该对象来加载模板。 在某些情况下,并排使用不同配置的多个环境可能会很有用。

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


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 /目录中查找模板的加载器。 可以使用不同的加载程序,如果要从数据库或其他资源加载模板,也可以编写自己的加载程序。

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.

请注意,环境的第二个参数是选项数组。 缓存选项是一个编译缓存目录,Twig在其中缓存已编译的模板,以避免后续后续请求的解析阶段。 它与您可能要为评估模板添加的缓存有很大不同。 为此,您可以使用任何可用的PHP缓存库。

Rendering Templates


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

要从Twig环境中加载模板,请调用load()方法,该方法返回一个\ Twig \ TemplateWrapper实例:

$template = $twig->load('index.html');

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


echo $template->render(['the' => 'variables', 'go' => 'here']);

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


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


echo $twig->render('index.html', ['the' => 'variables', 'go' => 'here']);

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


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实例时,可以将选项数组作为构造函数的第二个参数传递:

$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).


charset string (defaults to utf-8)


The charset used by the templates.


cache string or false


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


auto_reload boolean


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.


strict_variables boolean


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


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


optimizations integer


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




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; and the performance boost is even larger if you use a PHP accelerator such as OPCache. See the cache and auto_reload options of \Twig\Environment above for more information.

所有模板加载程序都可以在文件系统上缓存已编译的模板,以备将来重用。 模板只编译一次,因此可以大大提高Twig的速度。 如果使用PHP加速器(例如OPCache),则性能提升甚至更大。 有关更多信息,请参见上面\ Twig \ Environment的cache和auto_reload选项。

Built-in Loaders


Here is a list of the built-in loaders:



\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 \ FilesystemLoade 从文件系统加载模板。 该加载器可以在文件系统上的文件夹中找到模板,并且是加载它们的首选方式:

$loader = new \Twig\Loader\FilesystemLoader($templateDir);

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


$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:




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):


$loader->addPath($templateDir, 'admin');

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

命名空间模板可以通过特殊的@ namespace_name / template_path表示法进行访问:

$twig->render('@admin/index.html', []);

\Twig\Loader\FilesystemLoader support 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支持绝对路径和相对路径。 首选使用相对路径,因为它使高速缓存键独立于项目根目录(例如,它允许从构建服务器预热高速缓存,其中目录可能不同于生产服务器上使用的目录):

$loader = new \Twig\Loader\FilesystemLoader('templates', getcwd().'/..');

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



\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数组加载模板。 它传递了绑定到模板名称的字符串数组:

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

该加载器对于单元测试非常有用。 它也可以用于小型项目,在这些项目中,将所有模板存储在单个PHP文件中可能很有意义。

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 delegates the loading of templates to other loaders:

\ Twig \ Loader \ ChainLoader将模板的加载委托给其他加载器:

$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加载。

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


Create your own Loader


All loaders implement the \Twig\Loader\LoaderInterface:

所有加载程序都实现\ Twig \ Loader \ LoaderInterface:

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.


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()方法注册扩展:

$twig->addExtension(new \Twig\Extension\SandboxExtension());

Twig comes bundled with the following extensions:

TwigExtensionCoreExtension: Defines all the core features of Twig.

TwigExtensionDebugExtension: Defines the dump function to help debug template variables.

TwigExtensionEscaperExtension: Adds automatic output-escaping and the possibility to escape/unescape blocks of code.

TwigExtensionSandboxExtension: Adds a sandbox mode to the default Twig environment, making it safe to evaluate untrusted code.

TwigExtensionProfilerExtension: Enabled the built-in Twig profiler.

TwigExtensionOptimizerExtension: Optimizes the node tree before compilation.

TwigExtensionStringLoaderExtension: Defined the template_from_string








function to allow loading templates from string in a template.

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



Built-in Extensions

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



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


Core Extension

The core extension defines all the core features of Twig:







Escaper Extension

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

Escape扩展程序将自动输出转义添加到Twig。 它定义了一个标记,自动转义和一个原始过滤器。

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


$escaper = new \Twig\Extension\EscaperExtension('html');


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


{{ article.to_html|raw }}

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


{% autoescape 'html' %}

    {{ var }}

    {{ var|raw }}      {# var won't be escaped #}

    {{ var|escape }}   {# var won't be double-escaped #}

{% endautoescape %}

The autoescape tag has no effect on included files.


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:


{{ "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:


{{ 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()将某些类和/或接口标记为对某些策略安全:

// 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:


{{ var|upper }} {# is equivalent to {{ var|upper|escape }} #}

The raw filter should only be used at the end of the filter chain:


{{ 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标记为所有事物安全。

{% 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 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带有一个策略类:\ Twig \ Sandbox \ SecurityPolicy。 此类允许您将一些标签,过滤器,属性和方法列入白名单:

$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对象的title,body公共属性的getTitle()和getBody()方法。 其他所有内容均将被禁止,并将生成\ Twig \ Sandbox \ SecurityError异常。

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


$sandbox = new \Twig\Extension\SandboxExtension($policy);


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


{% sandbox %}

    {% include 'user.html' %}

{% endsandbox %}

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


$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模板启用了探查器; 它仅应在开发机器上使用,因为它会增加一些开销:

$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 compatible format:


$dumper = new \Twig\Profiler\Dumper\BlackfireDumper();

file_put_contents('/path/to/', $dumper->dump($profile));

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


blackfire --slot=7 upload /path/to/

Optimizer Extension

The optimizer extension optimizes the node tree before compilation:



$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:

默认情况下,所有优化都是打开的。 您可以通过将它们传递给构造函数来选择要启用的对象:

$optimizer = new \Twig\Extension\OptimizerExtension(\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR);


Twig supports the following optimizations:

\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_ALL, enables all optimizations (this is the default value).

\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_FOR, optimizes the for tag by removing the loop variable creation whenever possible.

\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_RAW_FILTER, removes the raw filter whenever possible.

\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS, simplifies the creation and access of variables in the compiled templates whenever possible.


\ Twig \ NodeVisitor \ OptimizerNodeVisitor :: OPTIMIZE_ALL,启用所有优化(这是默认值)。

\ Twig \ NodeVisitor \ OptimizerNodeVisitor :: OPTIMIZE_NONE,禁用所有优化。 这样可以减少编译时间,但是可以增加执行时间和占用的内存。

\ Twig \ NodeVisitor \ OptimizerNodeVisitor :: OPTIMIZE_FOR通过尽可能地删除循环变量的创建来优化for标记。

\ Twig \ NodeVisitor \ OptimizerNodeVisitor :: OPTIMIZE_RAW_FILTER,尽可能删除原始过滤器。

\ Twig \ NodeVisitor \ OptimizerNodeVisitor :: OPTIMIZE_VAR_ACCESS,尽可能简化了已编译模板中变量的创建和访问。


Twig can throw exceptions:

\Twig\Error\Error: The base exception for all errors.

\Twig\Error\SyntaxError: Thrown to tell the user that there is a problem with the template syntax.

\Twig\Error\RuntimeError: Thrown when an error occurs at runtime (when a filter does not exist for instance).

\Twig\Error\LoaderError: Thrown when an error occurs during template loading.

\Twig\Sandbox\SecurityError: Thrown when an unallowed tag, filter, or method is called in a sandboxed template.



\ Twig \ Error \ Error:所有错误的基本异常。

\ Twig \ Error \ SyntaxError:告诉用户模板语法有问题。

\ Twig \ Error \ RuntimeError:在运行时发生错误时抛出(例如,当过滤器不存在时)。

\ Twig \ Error \ LoaderError:在模板加载期间发生错误时抛出。

\ Twig \ Sandbox \ SecurityError:在沙盒模板中调用不允许的标签,过滤器或方法时抛出。