如桂枝大多數的事情,這可以通過在嫩枝
延伸
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