如桂枝大多数的事情,这可以通过在嫩枝
延伸
Twig
ProjectTwigExtension.php
class ProjectTwigExtension extends Twig_Extension {
public function getFunctions() {
return array(
new Twig_SimpleFunction('extract', array($this, 'extract'), ['needs_context' => true, ]),
);
}
public function extract(&$context, $value) {
foreach($value as $k => $v) $context[$k] = $v;
}
public function getName() {
return 'ProjectTwigExtension';
}
}
注册类完成
$twig = new Twig_Environment($loader);
$twig->addExtension(new ProjectTwigExtension());
template.twig
{{ extract({'foo': 'bar', }) }}
{{ foo }} {# output : bar #}
(阿里纳斯)好像你不能用一个封闭做到这一点(见下面的例子),因为Twig
编译器传递变量在一个阵列中,从而创建一个副本
随着封闭
$twig->addFunction(new Twig_SimpleFunction('extract', function (&$context, $value) {
foreach($value as $k => $v) $context[$k] = $v;
}, ['needs_context' => true, ]));
编译结果
echo twig_escape_filter($this->env, call_user_func_array($this->env->getFunction('extract')->getCallable(), array($context, array("foo" => "bar", "foobar" => "foo"))), "html", null, true);
谢谢深入的解决方案DarkBee。我从来没有想到会像这样令人费解,但它确实有效。我正在与Craft CMS合作,所以你提到的旁注最终并不适用于我。再次感谢,非常高兴! –
好赶上!它会取代现有的变量?例如foo已经在上下文中定义了吗?或者给出错误?仅用于好奇... – Matteo
当前代码将覆盖上下文中的任何现有变量 – DarkBee