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


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

配置Twig为应用程序加载模板的典型方法大致如下:


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:

要使用一些变量渲染模板,请调用render()方法:


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


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

display()方法是输出渲染的模板的快捷方式。


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:

如果模板定义了块,则可以通过renderBlock()调用分别渲染它们:


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

设置为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选项提供值,它将根据调试值自动确定。



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将静默忽略无效变量(变量和/或不存在的属性/方法),并将其替换为空值。设置为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.)

设置默认的自动转义策略(名称,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; 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

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

您可以通过addPath()和prependPath()方法添加或添加路径:


$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()方法时,将名称空间指定为第二个参数(如果未指定,则这些方法将作用于“主”名称空间):


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


$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

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

您也可以通过addLoader()方法添加加载程序。


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.

如果当前的缓存模板仍然是最新的(给定上次修改时间),则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()方法注册扩展:


$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


TwigExtensionCoreExtension:定义Twig的所有核心功能。

TwigExtensionDebugExtension:定义转储函数以帮助调试模板变量。

TwigExtensionEscaperExtension:添加自动转义转义以及对代码块进行转义/转义的可能性。

TwigExtensionSandboxExtension:将沙箱模式添加到默认的Twig环境中,从而可以安全地评估不受信任的代码。

TwigExtensionProfilerExtension:启用内置的Twig分析器。

TwigExtensionOptimizerExtension:在编译之前优化节点树。

TwigExtensionStringLoaderExtension:定义了template_from_string


function to allow loading templates from string in a template.

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.

内置扩展

本节介绍了内置扩展添加的功能。


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:

核心扩展

核心扩展定义了Twig的所有核心功能:


Tags;

Filters;

Functions;

Tests.

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');

$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,则模板中的所有变量都将被转义(使用html转义策略),使用原始过滤器的变量除外:


{{ article.to_html|raw }}


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

您还可以使用autoescape标签在本地更改转义模式:


{% 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.

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:

直接在模板中用作变量或过滤器参数的文字(整数,布尔值,数组等)永远不会自动转义:


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

//将接口Foo的对象标记为对HTML策略安全

$escaper->addSafeClass('FooInterface', ['html']);


// mark object of class Foo as safe for the HTML and JS strategies

//将Foo类的对象标记为对HTML和JS策略安全

$escaper->addSafeClass('Foo', ['html', 'js']);


// mark object of class Foo as safe for all strategies

//将Foo类的对象标记为对所有策略均安全

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

$twig->addExtension($sandbox);


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:

您可以通过传递true作为扩展构造函数的第二个参数来沙盒化所有模板:


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

您也可以以Blackfire.io兼容格式转储数据:


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

上载配置文件以使其形象化(首先创建一个免费帐户):


blackfire --slot=7 upload /path/to/profile.prof


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->addExtension($optimizer);


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支持以下优化:


\ 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,尽可能简化了已编译模板中变量的创建和访问。


Exceptions

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可能引发异常:


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

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

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

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

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