bobthecow/mustache.php — pull request #82 by bobthecow (2012-03-01 15:44:30+00:00)
Title: Add a "helpers" implementation to 2.0-dev

In Mustache.php, "helpers" are implemented by injecting values into base of the context stack. This is very powerful, and also very simple. In my opinion, it's also spec compliant :)

Just like other values in the rendering context, helpers can be "lambdas" (suitable for services) or regular values (which are more akin to constants or global variables in PHP).

For example, if you want to add an i18n translation service to Mustache, you'd do something like this:

```php
addHelper('_i18n', function($text) {
// IRL, you would use something far more robust :)
$dictionary = array(
'Hello.' => 'Hola.',
'My name is {{ name }}.' => 'Me llamo {{ name }}.',
);

return array_key_exists($text, $dictionary) ? $dictionary[$text] : $text;
});

$tpl = $m->loadTemplate('{{#_i18n}}Hello.{{/_i18n}} {{#_i18n}}My name is {{ name }}.{{/_i18n}}');
$tpl->render(array('name' => 'Justin'));
```

And this would render:

Hola. Me llamo Justin.

... Pretty rad, eh?

This is implemented as a "frame 0" on the context stack. This means all data passed in to `render()` will end up in "frame 1", and will be able to mask helpers. Using the example above, if we passed in a *new* lambda as `_i18n`, the call to `{{#_i18n}}` would resolve to the new value rather than the helper. This is consistent with how the context stack works elsewhere in Mustache.