Theme variables

Hi,

I am trying to pass some variables into my theme. I have setup my theme class file like follows:

<?php
namespace Grav\Theme;

use Grav\Common\Theme;

class MyTheme extends Theme
{
    public static function getSubscribedEvents()
    {
        return [
            'onThemeInitialized' => ['onThemeInitialized', 0]
        ];
    }

    public function onThemeInitialized()
    {
        if ($this->isAdmin()) { 
            $this->active = false;
            return;
        }

        $this->enable([
            'onTwigSiteVariables' => ['onTwigSiteVariables', 0]
        ]);
    }

    public function onTwigSiteVariables()
    {
        $this->grav['twig']->myVariable = 'test';
    }
}

I would like to be able to access the variable myVariable within my theme’s header.

{{ myVariable }} doesn’t seem to work. What am I doing wrong?

Thanks,

I was able to achieve this by $this->grav['twig']->twig->addExtension(new Test());

You also need to have process: twig: true in your YAML file which I didn’t realise. I still don’t know how to just pass a variable over but this is just as good for my purpose.

You add an extension if you want to call a Twig function, like {{ doSomething() }} (see https://learn.getgrav.org/cookbook/plugin-recipes#output-some-php-code-result-in-a-twig-template), but simple variables can be added via onTwigSiteVariable.

You need to enable process.twig to the page header only if you put the Twig code in a Markdown page, otherwise in the Twig it should work just fine.