xp-forge/handlebars

Handlebars for XP Framework

v9.4.0 2024-03-24 14:28 UTC

README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.0+ Supports PHP 8.0+ Latest Stable Version

The Handlebars template language implemented for the XP Framework.

use com\handlebarsjs\HandlebarsEngine;

$engine= new HandlebarsEngine();
$transformed= $engine->render('Hello {{name}}', [
  'name' => 'World'
]);

Templating

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'
]);

Helpers supported

The following helpers are built in:

The "if" block

{{#if licence}}
  A licence is available
{{/if}}

{{#if licence}}
  A licence is available
{{else}}
  <em>Warning: No licence is available!</em>
{{/if}}

{{#if content}}
  Content
{{else if hub}}
  Hub
{{else}}
  Default
{{/if}}

The "unless" block

{{#unless licence}}
  <em>Warning: No licence is available!</em>
{{/unless}}

The "with" block

{{#with person}}
  Full name: {{firstName}} {{lastName}}
{{/with}}

The "each" block

<ul>
  {{#each students}}
    <li>Student's name: {{firstName}} {{lastName}}</li>
  {{/each}}
</ul>

All of the above block helpers support the else statement.

The "log" helper

{{log '"Hello", Frank\'s mother said.'}}
{{log 'No publishers for' category level="warn"}}

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(...);

Custom helpers

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)

Futher reading

https://handlebars-lang.github.io/spec/