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.

Plugins

How access to own class method in Twig

Started by Pavel 7 years ago · 2 replies · 4131 views
7 years ago

Hello. I want to write my own class method in PHP (I think I must create plugin by devtools at the beginning. That will be class where I'll add my method). In this method I want to get some data. Next I want to have access to this method in all templates(as instantiated object from this class) and set Twig variable to returned data from my method.

I cannot find example in Grav how to do it. So can you explain me step by step.

7 years ago

@pawel, A rough example might give you an idea to start from.

I presume you have already found the plugin tutorial where you can learn the basic structure of a plugin.

There are many events you can subscribe to and one of them is onTwigSiteVariables. This is where you should add any variables to Twig that need to be available to Twig during this process.

The following is a sketch of /user/plugins/myplugin/myplugin.php:

PHP
class MyPlugin extends Plugin
{
    public static function getSubscribedEvents()
    {
        return [
            'onPluginsInitialized' => ['onPluginsInitialized', 0]
        ];
    }

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

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

    /**
     * Add variables to Twig.
     */
    public function onTwigSiteVariables()
    {
        $twig = $this->grav['twig'];
        $twig->twig_vars['myClass'] = new MyClass();
        $twig->twig_vars['myVariable'] = $myVariable;
    }
}

In Twig, you can now call methods and properties of the instance of MyClass or access provided variables.

TWIG
{% set returnValue = myClass.myMethod() %}
{% set property = myClass.myProperty %}
{% set variable = myVariable %}

Hope this gives you an idea to start from...

7 years ago

Thanks for the explaination. I understood how I must process. I have made two plugins needed for me.

Suggested topics

Topic Participants Replies Views Activity
Plugins · by Rene, 1 week ago
2 44 1 week ago
Plugins · by Xavier, 4 weeks ago
2 54 4 weeks ago
Plugins · by Luka Prinčič, 7 years ago
3 1181 1 month ago
Plugins · by Sebastian van de Meer, 1 month ago
1 48 1 month ago
Plugins · by PIERROT Alain, 2 months ago
3 73 2 months ago