Process a twig template by using a string variable


I’m trying to process a twig template by using a twig string contained in a YAML string variable. Let’s make it a bit more clear with an example:


c: 'hello '


bar:  '{{config.a.b.c}},{{foo}}'


{% set twigobj = grav['twig'] %}
{% set foo = 'world' %}
{% set val = twigobj.processString(,{foo: foo}) %}

This actually set val to 'hello world'. The main issue is that I need to pass each time an array including the variables (e.g. foo) which are different from the standard ones (e.g. config, site, browser…)

There may be another way to achieve this without passing the in-template variables ?

Your feedback is greatly appreciated!

Not sure if there’s a better alternative way to do like you did.

For anyone looking, I found the solution in the Twig documentation here

The following variables are always available in templates:

  • _self: references the current template;
  • _context: references the current context;
  • _charset: references the current charset.

The example above:

{% set val = twigobj.processString(,{foo: foo}) %}

can be rewritten as:

{% set val = twigobj.processString(,_context) %}

I’m wondering now if there would be any reason to not pass $context as parameter of the processString() call inside the evaluateFunc() function at /system/src/Grav/Common/Twig/TwigExtension.php. If so, I can try to propose a patch that does this.