-
Notifications
You must be signed in to change notification settings - Fork 423
FILTERS pragma
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
Mustache_Exception_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.
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.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.