Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Process a twig template by using a string variable

Started by Muut Archive 10 years ago · 2 replies · 1562 views
10 years ago

Hi.

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:

config/a/b.yaml

TXT
c: 'hello '

config/site.yaml

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

templates/page.html.twig

TWIG
{% set twigobj = grav['twig'] %}
{% set foo = 'world' %}
{% set val = twigobj.processString(config.bar,{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!

10 years ago

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

10 years ago

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:

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

can be rewritten as:

TWIG
{% set val = twigobj.processString(config.bar,_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.

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1357 9 years ago
Archive · by Muut Archive, 9 years ago
2 936 9 years ago
Archive · by Muut Archive, 9 years ago
2 4066 9 years ago
Archive · by Muut Archive, 9 years ago
1 2955 9 years ago
Archive · by Muut Archive, 9 years ago
3 1121 9 years ago