The Handlebars template language implemented for the XP Framework.
use com\handlebarsjs\HandlebarsEngine;
$engine= new HandlebarsEngine();
$transformed= $engine->render('Hello {{name}}', [
'name' => 'World'
]);
Templates can be loaded from the file system. The following loads and transforms the template src/main/handlebars.handlebars:
use com\handlebarsjs\HandlebarsEngine;
$engine= (new HandlebarsEngine())->withTemplates('src/main/handlebars');
$transformed= $engine->transform('hello', [
'name' => 'World'
]);
Templates can also be declared inline:
use com\handlebarsjs\HandlebarsEngine;
$engine= (new HandlebarsEngine())->withTemplates(['test' => 'Hello {{name}}']);
$transformed= $engine->transform('hello', [
'name' => 'World'
]);
If you need more flexibility, you can implement and then pass instances of the following:
new com.github.mustache.InMemory([:string] $templates))
new com.github.mustache.FilesIn(string|io.Folder $arg, string[] $extensions)
new com.github.mustache.ResourcesIn(string|lang.IClassLoader $arg, string[] $extensions)
- (Your own implementation of
com.github.mustache.templates.Templates
)
The following helpers are built in:
All of the above block helpers support the else
statement.
To enable logging, pass either a closure or a util.log.LogCategory
instance to the engine:
use util\log\Logging;
use util\cmd\Console;
// Use a logger category:
$logger= Logging::named('trace')->toConsole();
// Or a closure:
$logger= function($args, $level) { Console::writeLine('[', $level, '] ', ...$args); };
$engine= (new HandlebarsEngine())->withLogger($logger);
$engine->render(...);
To add custom helpers, use withHelpers() and pass functions. The following yields Hello WORLD:
use com\handlebarsjs\HandlebarsEngine;
$engine= (new HandlebarsEngine())->withHelper('upper', function($node, $context, $options) {
return strtoupper($options[0]);
});
$transformed= $engine->render('Hello {{upper name}}', [
'name' => 'World'
]);
The parameters passed are the following:
- node: The current node, a
com.github.mustache.Node
instance - context: The current context, a
com.github.mustache.Context
instance - options: The resolved options passed, in the above case the string "World" (which is what name resolves to)