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

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Support

Accessing config from Twig macros

Started by Oliver Scholz 8 years ago · 3 replies · 1199 views
8 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?

8 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?

8 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 Thomas, 1 week ago
2 53 10 hours ago
Support · by Anna, 3 days ago
2 60 13 hours ago
Support · by Justin Young, 14 hours ago
1 30 14 hours ago
Support · by Duc , 1 week ago
2 65 5 days ago
Support · by Colin Hume, 1 week ago
2 56 5 days ago