1

A long time ago I asked how I could utilise the getGlobal method in Craft 2.x.

I'd like to know how best to do this in Craft 3?

1 Answer 1

2

There are two ways to achieve this:

Option 1

Add this in your plugin/module main init function:

      $twig = Craft::$app->view->getTwig(null, ['safe_mode' => false]);
      $twig->addGlobal('foo', 'bar');

That's it. You can call 'foo' in your template like this {{ foo }} // Output 'bar'

Option 2 (best)

In the root of your plugin/module directory, create a folder called 'twigextensions' if you don't already have one. Create a new file where you're going to define your globals. MyGlobals.php for example.

At the very top of your main plugin/module file, you need to add this:

use modules\myawesomemodile\twigextensions\MyGlobals;

... remembering to amend the plugin/module name, and the name of the file you created.

Then add the following to the same file. Only this needs to be inside your main init function:

Craft::$app->view->registerTwigExtension(new MyGlobals());

Lastly, in your new MyGlobals.php file. Add the following. Again changning the plugin/module names where appropriate.

namespace modules\myawesomemodule\twigextensions;

use modules\myawesomemodule\MyAwesomeModule;

use Craft;

class MyGlobals extends \Twig_Extension implements \Twig_Extension_GlobalsInterface
{

    public function getGlobals()
    {
        return array(
            'foo' => 'bar',
        );
    }
}

That's it. Like before, you can call 'foo' in your template like this {{ foo }} // Output 'bar'

Now I don't understand the technical reasons as to why one is better than the other. I prefer Option 2 because it permits me to add multiple globals. However, my old post was answered by Mats Mikkel Rummelhoff; who goes into this in a little more detail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.