问题
Twig 上下文永远不会存储在模板对象中,因此很难找到一种干净的方法来实现这一点。例如,以下 Twig 代码:
{% set test = 'Hello, world' %}
将编译为:
<?php
class __TwigTemplate_20df0122e7c88760565e671dea7b7d68c33516f833acc39288f926e234b08380 extends Twig_Template
{
/* ... */
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$context["test"] = "Hello, world";
}
/* ... */
}
正如您所看到的,继承的上下文不会通过引用传递给 doDisplay 方法,并且永远不会存储在对象本身中(例如$this->context = $context
)。这种设计允许模板可重复使用,并且内存友好。
解决方案1:使用全局变量
不知道你是否知道全局变量 http://twig.sensiolabs.org/doc/advanced.html#globals在树枝中。你可以用它们做很多黑客活动。
最简单的用法是将所有全局变量加载到 twig 环境中。
$loader = new Twig_Loader_Filesystem(__DIR__.'/view');
$env = new Twig_Environment($loader);
$env->addGlobal('foo', 'bar');
$env->addGlobal('Hello', 'world!');
然后,您可以使用{{ foo }}
and {{ Hello }}
在你的整个应用程序中。
但这里有两个问题:
解决方案 2:使用 Twig 扩展
您还可以创建一个存储扩展来提供save
函数将某些模板的上下文保留在某处,并且restore
函数将此存储的上下文合并到另一个存储的上下文中。
proof_of_concept.php
<?php
require __DIR__.'/vendor/autoload.php';
class StorageTwigExtension extends Twig_Extension
{
protected $storage = [];
public function getFunctions() {
return [
new Twig_SimpleFunction('save', [$this, 'save'], ['needs_context' => true]),
new Twig_SimpleFunction('restore', [$this, 'restore'], ['needs_context' => true]),
];
}
public function save($context, $name) {
$this->storage = array_merge($this->storage, $context);
}
public function restore(&$context, $name) {
$context = array_merge($context, $this->storage);
}
public function getName() {
return 'storage';
}
}
/* usage example */
$loader = new Twig_Loader_Filesystem(__DIR__.'/view');
$env = new Twig_Environment($loader);
$env->addExtension(new StorageTwigExtension());
echo $env->render('test.twig'), PHP_EOL;
twig/variables.twig
{% set foo = 'bar' %}
{% set Hello = 'world!' %}
{{ save('test') }}
twig/test.twig
{% include 'variables.twig' %}
{{ restore('test') }}
{{ foo }}
Note: if you only want to import variables without actually rendering what's inside twig/variables.twig, you can also use:
{% set tmp = include('variables.twig') %}
{{ restore('test') }}
{{ foo }}
最后说明
我不习惯 JavaScript twig 端口,但看起来你仍然可以扩展它,那就是你的了:)