Skip to content
● Grav 2.2 is out: 2x faster cold starts and 96% less memory on big sites. Read the announcement →

Accessing config from Twig macros

Started by Oliver Scholz 9 years ago · 3 replies · 1562 views
9 years ago

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:

YAML
test: "hello"

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

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

And finally this in a template:

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

Then the resulting output is:

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

Is there a way around this?

9 years ago

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:

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?

9 years ago

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

Suggested topics

Topic Participants Replies Views Activity
Support · by webmasterodp, 7 days ago
4 151 6 days ago
Support · by nwhitfield, 1 week ago
2 131 1 week ago
Support · by stell, 3 weeks ago
5 364 2 weeks ago
Support · by gravinator, 1 month ago
5 556 2 weeks ago
Support · by Gravver, 3 weeks ago
6 344 3 weeks ago