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, FilesIn};
$engine= (new HandlebarsEngine())->withTemplates(new FilesIn('src/main/handlebars'));
$transformed= $engine->transform('hello', [
'name' => 'World'
]);
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(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)