Home - bobthecow/mustache.php GitHub Wiki

Mustache is a simple, logic-less template engine.

We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some with nothing, and others with a series of values.

Prerequisites

Mustache.php requires at least PHP 5.6 to run, but works great in the latest PHP versions too!

Installation

Use Composer. Add mustache/mustache to your project's composer.json:

{
    "require": {
        "mustache/mustache": "~3.0"
    }
}

Basic usage

<?php
$m = new \Mustache\Engine;
echo $m->render('Hello, {{planet}}!', ['planet' => 'World']); // "Hello, World!"

Constructor options

template_class_prefix

The class prefix for compiled templates. Defaults to __Mustache_.

cache

A Mustache Cache instance or cache directory for compiled templates. Mustache will not cache templates unless this is set.

cache_file_mode

Override default permissions for cache files. Defaults to using the system-defined umask. It is strongly recommended that you configure your umask properly rather than overriding permissions here.

cache_lambda_templates

Enable template caching for lambda sections. This is generally not recommended, as lambda sections are often too dynamic to benefit from caching.

delimiters

Customize the tag delimiters used by this engine instance. Note that overriding here changes the delimiters used to parse all templates and partials loaded by this instance. To override just for a single template, use an inline "change delimiters" tag at the start of the template file: {{=<% %>=}}.

loader

A Mustache template loader instance. Uses a StringLoader if not specified.

partials_loader

A Mustache loader instance for partials. If none is specified, defaults to an ArrayLoader for the supplied partials option, if present, and falls back to the specified template loader.

partials

An array of Mustache partials. Useful for quick-and-dirty string template loading, but not as efficient or lazy as a Filesystem (or database) loader.

helpers

An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order sections), or any other valid Mustache context value. They will be prepended to the context stack, so they will be available in any template loaded by this Mustache instance.

escape

An 'escape' callback, responsible for escaping double-mustache variables. Defaults to htmlspecialchars.

entity_flags

The type argument for htmlspecialchars. Defaults to ENT_COMPAT, but you may prefer ENT_QUOTES.

charset

Character set for htmlspecialchars. Defaults to UTF-8.

logger

A Mustache logger instance. No logging will occur unless this is set. Using a PSR-3 compatible logging library—such as Monolog—is highly recommended. A simple stream logger implementation is available as well.

lambdas

By default, "lambdas" are enabled; if a variable resolves to a callable value, that callable is called before interpolation. If a section name resolves to a callable value, it is treated as a "higher order section", and the section content is passed to the callable for processing prior to rendering.

Note that the FILTERS pragma requires lambdas to function, so using FILTERS without lambdas enabled will throw an invalid argument exception.

To disable lambdas and higher order sections entirely, set this to false.

inheritance

By default, templates can extend other templates using the {{< name}} and {{$ block}} tags. To disable template inheritance, set this to false.

dynamic_names

By default, variables and sections like {{*name}} will be resolved dynamically. To disable dynamic name resolution, set this to false.

pragmas

Enable pragmas across all templates, regardless of the presence of pragma tags in the individual templates.

strict_callables

Only treat \Closure instances and invokable classes as callable. If true, values like ['ClassName', 'methodName'] and [$classInstance, 'methodName'], which are traditionally "callable" in PHP, are not called to resolve variables for interpolation or section contexts. This helps protect against arbitrary code execution when user input is passed directly into the template.

Caution

Defaults to true, but can be set to false to preserve Mustache.php v2.x behavior. THIS IS NOT RECOMMENDED.

buggy_property_shadowing

Per the Mustache spec, keys of a value higher in the context stack shadow similarly named keys lower in the stack. For example, in the template {{# foo }}{{ bar }}{{/ foo }} if the value for foo has a method, property, or key named bar, it will prevent looking lower in the context stack for a another value named bar.

Setting the value of an array key to null prevents lookups higher in the context stack. The behavior should have been identical for object properties (and \ArrayAccess) as well, but a bug in the context lookup logic meant that a property which exists but is set to null would not prevent further context lookup.

Caution

This bug was fixed in Mustache.php v3.x, but the previous buggy behavior can be preserved by setting this option to true. THIS IS NOT RECOMMENDED.

double_render_lambdas

Double-render lambda return values. By default, the return value of higher order sections that are rendered via the lambda helper will not be re-rendered.

Caution

To preserve the behavior of Mustache.php v2.x, set this to true. THIS IS NOT RECOMMENDED.

Using these options

<?php

$mustache = new \Mustache\Engine([
    'template_class_prefix' => '__MyTemplates_',
    'cache' => __DIR__ . '/tmp/cache/mustache',
    'cache_file_mode' => 0666, // Please, configure your umask instead of doing this :)
    'cache_lambda_templates' => true,
    'loader' => new \Mustache\Loader\FilesystemLoader(__DIR__ . '/views'),
    'partials_loader' => new \Mustache\Loader\FilesystemLoader(__DIR__ . '/views/partials'),
    'helpers' => ['i18n' => function($text) {
        // do something translatey here...
    }],
    'escape' => function($value) {
        return htmlspecialchars($value, ENT_COMPAT, 'UTF-8');
    },
    'charset' => 'ISO-8859-1',
    'logger' => new \Mustache\Logger\StreamLogger('php://stderr'),
    'pragmas' => [\Mustache\Engine::PRAGMA_FILTERS],
]);

$tpl = $mustache->loadTemplate('foo'); // loads __DIR__ . '/views/foo.mustache';
echo $tpl->render(['bar' => 'baz']);

Further documentation

⚠️ **GitHub.com Fallback** ⚠️