问题
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