树枝变量作为参考

问题描述 投票:0回答:1

我正在尝试通过php参考更改Twig变量,但我无法实现。我环顾四周,也没有使用Twig函数或Twig过滤器,我可以做我想做的事。知道怎么做吗?

{% set hiding_options_classes = "default" %}
{{ hiding_options_func(content.field_hiding_options, hiding_options_classes) }}
{{ hiding_options_classes }}

在我的Twig扩展名文件中:

public function hiding_options_func($hiding_options, &$hiding_options_classes) {
    $hiding_options_classes = "coucou";
}
php symfony twig drupal-8
1个回答
0
投票

如果您想在扩展程序中更改变量,则需要通过引用传递上下文。

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 #}
© www.soinside.com 2019 - 2024. All rights reserved.