letrollpoilu
letrollpoilu

Reputation: 125

Twig variables as references

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

Upvotes: 0

Views: 943

Answers (1)

DarkBee
DarkBee

Reputation: 15623

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

Upvotes: 3

Related Questions