小枝变量作为参考 [英] Twig variables as references
本文介绍了小枝变量作为参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过php参考更改Twig变量,但我无法实现.我环顾四周,也没有使用Twig函数或Twig过滤器,我可以做我想做的事.知道怎么做吗?
I'm trying to change a Twig variable via a php reference but I can't achieve that. I looked around and nor with Twig functions nor with Twig filters I could do what I want. Any idea how to do that?
{% set hiding_options_classes = "default" %}
{{ hiding_options_func(content.field_hiding_options, hiding_options_classes) }}
{{ hiding_options_classes }}
在我的Twig扩展文件中:
In my Twig extension file:
public function hiding_options_func($hiding_options, &$hiding_options_classes) {
$hiding_options_classes = "coucou";
}
推荐答案
如果您想在扩展程序中更改变量,则需要通过引用传递上下文.
You would need to pass the context by reference if you wanted to change variables inside your extension e.g.
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension {
public function getFunctions() {
return [
new \Twig\TwigFunction('set', [$this, 'setValue'], ['needs_context' => true, ]),
];
}
public function setValue(&$context, $key, $value) {
if (isset($context['_parent'])) $context['_parent'][$key] = $value;
$context[$key] = $value;
}
}
{% set foo = 'bar' %}
{{ foo }} {# out: bar #}
{% do set('foo', 'foo') %}
{{ foo }} {# out: foo #}
这篇关于小枝变量作为参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文