I can’t get $this->grav['twig']->twig_vars() to work. (I can’t even find the function in Grav API documentation).
I have tried to duplicate code in the login and form plugins.
I want to create a protect variable $myvar in a plugin class. Then I want to update $myvar in a custom form, eg., $this->myvar['operator'] = $data['operator'] (inside onFormProcessed(). This all works as expected and I can see $myvar in a debugger bar after dumping it.
Now I want to render the new value in twig, eg., in default.md I have the content line {{ myvar.operator }}
So I thought if I put the following in onTwigSiteVariables:
I had this recently. It seems that you need to use the method $this->grav['twig']->twig->addGlobal():
// ... Inside Plugin Class
public $myVar;
// You need to enable this in getSubscribedEvents()
public function onTwigExtensions()
{
if ($this->isAdmin()) {
return;
}
$this->grav["twig"]->twig->addGlobal('myVar', $this->myVar);
}
// ...
I found that some of my problems were eliminated when I tried the plugin on a clean Grav skeleton with minimal other plugins. I’m not sure what causes the problems in my full site, but now I have got something working.
The function twig_vars may not be entirely what I need. There is a problem about order. If the call to twig_vars is before the assignment to the variable, then any new assignment is not picked up. Thus:
\\in plugin class
public $myVar;
\\ in onPluginInitialized
$this->grav['twig']->twig_vars['myVar'] = $myVar;
$this->myVar['one'] = 'something interesting';
\\ in default.md
{{ myVar.one }}
I realize that this can be overcome by placing the twig_vars reference in another callback. However, it seems that twig_vars is putting a copy of the variable into the twig area, and not a reference to the variable that can be updated.
Eg. putting the twig_vars call into onTwigExtensions works as desired.
$this->grav['twig']->addGlobal('myVar', $this->myVar) does not work in onPluginsInitialized.
I don’t know whether twig_vars[] and twig->addGlobal() are equivalent.