There are multiple contexts in Vanilla where you may want to render a twig view.
In a Gdn_Controller
This is very easy. Follow the rules for naming views as defined in our views documentation. Then use the file extension .twig
instead of .php
.
View overrides, lookup, etcetera, all work exactly the same as with a PHP or Smarty view.
In a non-controller class instance
In contexts where we don't have a controller we may still need to render some HTML. One example of this would be in user content or embeds. These functions may be run in multiple contexts such as an API or Message Queue Job.
To render items in this case, apply the TwigRenderTrait
to your class, and use the exposed method ->renderTwig($view, $data)
.
Example
class MyClass {
use TwigRenderTrait;
public function renderSomeHtml(): string {
return $this->renderTwig('@my-addon/components/my-component.twig', [
'param1' => 'Param Value'
]);
}
}
In a static context
Sometimes we have a static or global method that requires rendering some HTML. In these cases it is not possible to use the renderTwig()
method exposed by the twig render trait.
Instead similar functionality can be achieved by using TwigStaticRenderer::renderTwigStatic($viewPath, $data)
.
Example
function oldGlobalFunction(): string {
return TwigStaticRenderer::renderTwigStatic(
'@my-addon/components/my-component.twig',
['param1' => 'Param Value']
);
}
View Aliases
Twig provides some aliases to simplify view paths. The mapping goes from @addon-key
-> the addon's view directory.
Example
An addon with the key my-addon
has a view located at /plugins/my-addon/views/components/my-component.twig
. This view may be accessed with the following alias:
@my-addon/components/my-component.twig