Handlebars: Change Context

Custom helpers can render the inner block with new context

This is a handlebars.js extension, mustache do not support this.

Samples


lightncandy

Used option: FLAG_THIS

Data:
array(
  "bar" => "World"
)
Template:
{{#foo}}Hello, {{this}}{{/foo}}
Result:
Hello, World

Check the code to know used helper codes

Source Code
require('./vendor/autoload.php');
use LightnCandy\LightnCandy;
$template = "{{#foo}}Hello, {{this}}{{/foo}}";

$php = LightnCandy::compile($template, array(
  "flags" => LightnCandy::FLAG_THIS,
  "helpers" => array(
    "foo" => function ($options) {
        // Apply child 'bar' of current context into inner block
        return $options['fn']($options['_this']['bar']);
    }
  )
));
$render = LightnCandy::prepare($php);
$data = array(
  "bar" => "World"
);
echo $render($data);
handlebars.js
Data:
{
  "bar": "World"
}
Template:
{{#foo}}Hello, {{this}}{{/foo}}
Result:
Hello, World

Check the code to know used helper codes

Source Code
var Handlebars = require('handlebars');
var template = '{{#foo}}Hello, {{this}}{{/foo}}';

Handlebars.registerHelper({
  'foo': function (options) {
      // Apply child 'bar' of current context into inner block
      return options['fn'](this['bar']);
  }
});
var render = Handlebars.compile(template);
var data = {
  "bar": "World"
};
console.log(render(data));

See Also...