Twig variables as references

生来就可爱ヽ(ⅴ<●) 提交于 2021-01-29 09:16:01

问题


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 }}

In my Twig extension file:

public function hiding_options_func($hiding_options, &$hiding_options_classes) {
    $hiding_options_classes = "coucou";
}

回答1:


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 #}


来源:https://stackoverflow.com/questions/59247917/twig-variables-as-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!