Ceagle
Ceagle

Reputation: 337

How do I get a Twig Variable I set from my twig extension?

So.. I've been trying for awhile to get twig variables in my extension.

First I tried getting from $environment->getGlobals().. But that was just that, indeed, just globals. Then I tried referencing different parts inside of getCompiler(), no juice, many thing I tried instead just locked up my browser or php instance.

So what am I trying to do?

In my twig template I'm doing this

{% set myvariable = "something" %}

In my twig extension when I call a specific function I want to see if this variable was set something, if it was set something I want to perform a specific action.

Upvotes: 4

Views: 2641

Answers (3)

Linkmichiel
Linkmichiel

Reputation: 2130

You can pass twig variables to your twig extension by passing the global variable _context to your function. _context is an array which holds all variables from your template.

{{ my_twig_function(_context) }}

Upvotes: 0

Sean Quinn
Sean Quinn

Reputation: 2171

Have you looked at Twig's Global Variables for Templates? I was looking for something similar (a mechanism to get all variables set in the context of a template) and stumbled across the _context global variable which held everything that I needed.

Upvotes: 0

Henrik Bjørnskov
Henrik Bjørnskov

Reputation: 529

If you can get access to the context from where your extension is called then you should be able to figure it out.

Upvotes: 0

Related Questions