FILTERS pragma - bobthecow/mustache.php GitHub Wiki
The {{% FILTERS }} pragma enables a handy pipe-notation for filtering values prior to interpolation:
{{ greeting | case.lower }}
More specifically:
- Pipe notation is analogous to dot notation — it can be thought of as syntactic sugar for nested sections.
- Filters are just variables in the normal context stack.
- With that in mind, name your filters carefully
- If you encounter an unexpected
UnknownFilterException, it's possible your filter's name conflicts with an existing context variable
- Values are not coerced into strings (or escaped) until they come out the other end of the pipe.
- Unlike nested sections, the first value in the pipe is fetched prior to passing it to the next lambda.
- If any filter is not found, or is non-callable, an UnexpectedValueException is thrown.
- Filters are only available for interpolation (
{{ foo }}) and section({{# foo }}or{{^ foo }}) tags. You can't use 'em in partial tags. (are Pragma are executed only on template itself, doesn't work on{{< partial }}or parent{{% BLOCKS }} - Filters are not intended to replace a proper View or ViewModel. While they can be (ab)used to add logic to your templates, please resist the temptation and keep your logic in code.
[!NOTE] If a filter is missing or resolves to a non-callable value, Mustache.php will throw an
UnknownFilterException. Define the filter as a helper, or check whether a context value is shadowing the helper name.
In practice, they look something like this:
<?php
$mustache = new \Mustache\Engine;
$mustache->addHelper('case', [
'lower' => function($value) { return strtolower((string) $value); },
'upper' => function($value) { return strtoupper((string) $value); },
]);
$mustache->addHelper('!!', function($value) { return $value . '!!'; });
$tpl = <<<TPL
{{%FILTERS}}
{{ greeting | case.lower }}, {{ planet | case.upper | !! }}
TPL;
echo $mustache->render($tpl, [
'greeting' => 'Hello',
'planet' => 'world',
]);
// "hello, WORLD!!"
See mustache/spec#41 for the discussion on including this pragma in the Mustache spec.
[!NOTE] See the Helper and filter cookbook for examples of common helpers, filtered sections, PHP-style
foreachiteration, loop state, and boolean list tests.