Skip to content
Km edited this page Feb 12, 2022 · 8 revisions

The {{% FILTERS }} pragma enables a handy pipe-notation for filtering values prior to interpolation:

{{ greeting | case.lower }}

More specifically:

  1. Pipe notation is analogous to dot notation — it can be thought of as syntactic sugar for nested sections.
  2. Filters are just variables in the normal context stack.
    1. With that in mind, name your filters carefully
    2. If you encounter an unexpected Mustache_Exception_UnknownFilterException, it's possible your filter's name conflicts with an existing context variable
  3. Values are not coerced into strings (or escaped) until they come out the other end of the pipe.
  4. Unlike nested sections, the first value in the pipe is fetched prior to passing it to the next lambda.
  5. If any filter is not found, or is non-callable, an UnexpectedValueException is thrown.
  6. 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 }}
  7. 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.