Using the Fluid Template Engine in WordPress #
One of the essential things missing in WordPress, is a template engine. In WordPress, templates are written in PHP – and often this makes the code very illegible.
The nnhelpers
plugin ships with a standalone version of the Fluid Template Engine. This is one of the best template engines out there. It has a long development history, is fast, robust and can easily be extended with custom ViewHelpers.
After installing the nnhelpers-Plugin You can use the Fluid-Template-Engine anywhere in the code of your own WordPress-template like this:
Example #
$vars = [
'name' => 'John',
'hobbies' => ['coding', 'eating', 'fishing']
];
echo \nn\wp::Template()->render( 'EXT:yourplugin/path/to/template.html', $vars );
The EXT:
is a special placeholder that will be resolved to the path of your plugin (wp-content/plugins/...
). Your Template file could look like this:
<h1>Thing that {name} loves doing:</h1>
<ul>
<f:for each="{hobbies}" as="hobby">
<li>{hobby}</li>
</f:for>
</ul>
Setting Partials- / Layouts- / Template-Rootpaths #
$view = \nn\wp::Template();
$view
->setLayoutRootPaths(['EXT:myplugin/Resources/Layouts/'])
->setPartialRootPaths(['EXT:myplugin/Resources/Partials/'])
->setTemplateRootPaths(['EXT:myplugin/Resources/Templates/'])
->assignMultiple(['a'=>123])
->render('Show');
Alternativ to render(): #
$view = \nn\wp::Template();
$view
->setTemplate('Show')
->render();
Registering additional ViewHelpers #
The following code will register an additional ViewHelper namespace that can be used inside of the Fluid-template with {vh:name()}
and <vh:name />
$view = \nn\wp::Template();
$view
->addViewHelperNameSpace('vh', 'My\\Example\\ViewHelpers')
->render( 'EXT:example/path/to/Template.html');