简体   繁体   中英

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.

如果您可以访问调用扩展程序的上下文,那么您应该能够找到它。

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM