Accessing config from Twig macros

Hello!

It seems that it’s not possible to access configuration values from within a Twig macro. For instance, if I have this in <theme-directory>/<theme-name>.yaml:

test: "hello"

And a macro in macros/test.html.twig:

{% macro test() %}
  <h2>Macro: {{ config.theme.test }}</h2>
{% endmacro %}

And finally this in a template:

  {% import 'macros/test.html.twig' as test %}
  <h2>Outside macro: {{ config.theme.test }}</h2>
  {{ test.test() }}

Then the resulting output is:

    <h2>Outside macro: hello</h2>
    <h2>Macro: </h2>

Is there a way around this?

Answering my own post (sorry for that). After fooling around for a bit, it seems that one “way around this” would be to extend Twig with a function.

In <my theme dir>/<my theme name>.php:

class <my theme name> extends Theme
{
    // Access plugin events in this class
    
    public function onTwigExtensions()
    {
        if ($this->isAdmin()) {
            $this->active = false;
            return;
        }
        $function = new \Twig_SimpleFunction('my_test', function (String $my_var) {
            $my_other_var = $this->grav['config']['theme']['test'];
            return "Hello, $my_var and $my_other_var!";
        });
        $this->grav['twig']->twig->addFunction($function);
    }
}

And then in a template I can do: {{ my_test("Test") }}.

For the real life case behind my question this is actually more elegant. Doing it in a plugin would be even better. I was just hoping to postpone things like that until I’m more familiar with the basics. Are there any obvious stylistic weirdnesses with the PHP above?

Hi @Utis, another way to do this is to pass the needed config to the Macro itself, here is an example:

Hope the above might also be helpful to you🙂

1 Like

Hey, yeah, that might come in handy on similar occasions when extending Twig would be overkill. Thanks!