A Mustache implementation in PHP.



A Mustache implementation in PHP.

Package version Build status StyleCI Monthly downloads


A quick example:

$m = new Mustache_Engine(array('entity_flags' => ENT_QUOTES));
echo $m->render('Hello {{planet}}', array('planet' => 'World!')); // "Hello World!"

And a more in-depth example -- this is the canonical Mustache template:

Hello {{name}}
You have just won {{value}} dollars!
Well, {{taxed_value}} dollars, after taxes.

Create a view "context" object -- which could also be an associative array, but those don't do functions quite as well:

class Chris {
    public $name  = "Chris";
    public $value = 10000;

    public function taxed_value() {
        return $this->value - ($this->value * 0.4);

    public $in_ca = true;

And render it:

$m = new Mustache_Engine(array('entity_flags' => ENT_QUOTES));
$chris = new Chris;
echo $m->render($template, $chris);

Note: we recommend using ENT_QUOTES as a default of entity_flags to decrease the chance of Cross-site scripting vulnerability.

And That's Not All!

Read the Mustache.php documentation for more information.

See Also

  • PHP 5.2 compatibility

    PHP 5.2 compatibility

    I noticed that the dev version (2.0) uses namespaces, a PHP 5.3 only feature.

    Is there any particular reason why PHP 5.2 can't be supported?

    For example, I will not be able to upgrade to 2.0 when it comes out, since my WordPress plugins can't assume a PHP 5.3 environment.

    opened by scribu 36
  • internationalization with Mustache and sprintf

    internationalization with Mustache and sprintf

    Sorry if this might seem as a double-post from stack-overflow (http://stackoverflow.com/questions/8695970/mustache-i18n-with-parameters/) but I'm really struggling with this and would appreciate any pointers.

    I've read about higher order sections, and even though lambdas generally confuse me, I think I managed to implement something basic to do i18n of simple text with Mustache (I can copy&paste the code, but it's already on SO).

    However, I'd really like to find a good (or reasonable) replacement for things like sprintf(__('translated %s with parameters'), $string)

    Can anybody suggest something? Did I miss something obvious (or not so obvious)?

    opened by gingerlime 22
  • Mustache Php Performance

    Mustache Php Performance

    We have a serious issue with the performance of the Mustache. Mustach is recursive, and use "preg_match" a lot. Rendering can take sometimes up to 3 sec per page loading. Is there a way to cache most of the work Mustach is doing per template? I mean, theoretically, Mustach could cache the positions, or the results of all the "preg_match" invocations, and then just simply replace the result, with the given render parameters. Couldn't that speed up 90% of the rendering work?

    opened by ndvbd 22
  • Implement template inheritance via `{{% BLOCKS }}` pragma.

    Implement template inheritance via `{{% BLOCKS }}` pragma.

    This is a proof-of-concept implementation of template inheritance via blocks.

    Say we have a template named layout.mustache. This would be our generic site layout template, consisting of all the sorts of things you'd expect in a layout template. In addition, it would have a number of blocks defined. The blocks look like Mustache sections, but they're denoted with {{$ block }} tags instead of #.

    <!-- layout.mustache -->
    {{% BLOCKS }}
    <!DOCTYPE html>
        <title>{{$ title }}My Alsome Site{{/ title }}</title>
        {{$ stylesheets }}
          <link rel="stylesheet" href="/assets/css/default.css">
        {{/ stylesheets }}
          {{$ header }}
            <h1>Welcome to My Alsome Site</h1>
          {{/ header }}
        <section id="content">
          {{$ content }}
            <p>Hello, World!</p>
          {{/ content }}
        {{$ scripts }}
          <script src="/assets/js/default.js"></script>
        {{/ scripts }}

    The blocks defined here are {{$ title }}, {{$ stylesheets }}, {{$ header }}, {{$ content }} and {{$ scripts }}.

    By default, blocks merely delineate sections of the template which can be extended (replaced) in subtemplates. If the parent template itself is rendered, the block tags are simply rendered as if they are truthy sections.

    This layout template can then be extended by other sub-templates, which declare their intention by adding a parent=layout to the {{% BLOCKS }} pragma tag:

    <!-- page.mustache -->
    {{% BLOCKS parent=layout}}
    {{$ title }}My Alsome Page{{/ title }}
    {{$ stylesheets }}
      <link rel="stylesheet" href="/assets/css/page.css">
    {{/ stylesheets }}
    {{$ header }}
      <h1>My page has some items!</h1>
    {{/ header }}
    {{$ content }}
        {{# items }}
          <li><a href="{{ link }}" title="{{ name }}">{{ name }}</a></li>
        {{/ items }}
    {{/ content }}

    Upon rendering this page.mustache, the subtemplate blocks will be substituted for the parent blocks, resulting in (approximately) this:

    <!DOCTYPE html>
        <title>My Alsome Page</title>
        <link rel="stylesheet" href="/assets/css/page.css">
          <h1>My page has some items!</h1>
        <section id="content">
            {{# items }}
              <li><a href="{{ link }}" title="{{ name }}">{{ name }}</a></li>
            {{/ items }}
        <script src="/assets/js/default.js"></script>

    In our example, we didn't override every block: the {{$ scripts }} block retained its default value. We could also create a new subtemplate which extends page.mustache, say custom-page.mustache. That subtemplate might only replace the {{$ content }} block of page.mustache, and inherit the rest.

    Note that page.mustache could even define new blocks. Maybe add a {{$ main }} and {{$ complimentary }} section inside {{$ content }}:

    {{$ content }}
      <div id="main" role="main">
        {{$ main }}{{/ main }}
      <div id="complimentary" role="complimentary">
        {{$ complimentary }}{{/ complimentary }}
    {{/ content }}

    Then sub-subtemplates could choose to override just the {{$ main }} block, while leaving {{$ content }} and {{$ complimentary }} intact.

    opened by bobthecow 21
  • Extract cache interface

    Extract cache interface

    (Alternative to #165)

    Refactoring to allow for alternative cache implementations. Includes implementations for the default noop (i.e. un-cached) behavior and a filesystem-based cache whose configuration is consistent with the existing Mustache_Engine constructor.

    Includes updated and new tests.

    Two changes of note:

    1. Compiled template classes are now always eval'ed (rather than as an include_once)
    2. Logging differs

    To address the logging, Mustache_Cache could be implemented as an abstract class with get/setLogger and log implementations added to the interface. Not a fan of passing down the reference (hence why the logging was simply removed), but open to ideas.

    As for the eval, curious on your thoughts / fears.

    opened by amitsnyderman 20
  • possible don't use indent:

    possible don't use indent:

    • much less concatinations
    • much smaller page weight
    opened by nizsheanez 20
  • Pass a rendering helper to section lambdas

    Pass a rendering helper to section lambdas

    In addition to the section contents, section lambdas (higher order sections) would receive a lambda helper as a second parameter. This helper consists of a single render method, allowing a template to be rendered using the current context stack.

    The returned result from a section lambda is automatically rendered as a mustache template, which is sufficient most of the time. But if you want to do something with the rendered value of that template, it doesn't quite cut it.

    For example, this data:

    $data = array(
      'foo' => 'win',
      'embiggen' => function($text) {
        return strtoupper($text);

    ... and this template:

    {{#embiggen}}{{ foo }}{{/embiggen}}

    ... would uppercase the {{ FOO }} template string, rather than the value of foo. This would then be automatically rendered, resulting in an empty string, since there is no FOO value available.

    With this change, a mustache lambda helper is passed as the second parameter to the anonymous function, giving you a way to render the section value:

    $data = array(
      'foo' => 'win',
      'embiggen' => function($text, $mustache) {
        return strtoupper($mustache->render($text));

    ... which would render as WIN, exactly like you'd expect.

    In other languages (JavaScript, Ruby), this method would be bound to the closure context and just be available inside the anonymous function, but this isn't an option in PHP :)

    This change is backwards compatible, as the second value will simply be ignored by any section lambda not referencing it.

    opened by bobthecow 19
  • Add

    Add "anchored dot notation"

    1. Given that {{ . }} resolves as the top of the context stack;
    2. And when any falsey segment in a dotted name is encountered, the whole name yields '';
    3. A name like {{ .name }} should imply {{ [top of stack].name }};
    4. Thus, it must resolve as truthy only if a member of the top of the context stack matches name.

    There have been several syntaxes proposed (mustache/spec#10 and mustache/spec#11 as well as my mustache/spec#52). This one is my favorite because,

    • It introduces no new symbols, it simply allows combining two existing syntaxes into a single tag.
    • It is backwards compatible, meaning, no currently working code will be broken, since {{ .foo.bar }} isn't a valid variable name in the current spec.
    • It doesn't come with any of the crazy traversal logic that the {{ ../foo }} style anchors do, so I feel it's more in keeping with the logic-free nature of Mustache.
    • It doesn't involve blessing any valid variable names as super-variables (e.g. the proposed {{ this.foo }} syntax, which would be a backwards compatibility break, as well as limiting perfectly valid variable names in some languages.

    See spec discussion at mustache/spec#52 and some impetus at #98.

    This is a complete implementation, but it's currently missing tests. I'm torn on including it without a pragma, since it would technically make Mustache.php not spec compliant.


    opened by bobthecow 19
  • Using objects in sections

    Using objects in sections

    There's a couple problems here:

    1. _renderSection() checks for _varIsIterable() which checks for is_object(). This doesn't mean that the object is iterable. Then the elseif() in _renderSection() also checks for is_object() which is kinda weird (and probably proper in this case)
    2. A problem exists with the above logic in that if the object is iterable, it will do a foreach on the object, and you'll loose access to any object methods for variable replacement in your template.

    I'm trying to think of a good fix for this, as I think #2 is the real problem. It could possibly be fixed by just taking the is_object() check out of _varIsIterable().

    opened by zombor 18
  • Higher-order sections

    Higher-order sections

    The current higher-order section implementation in Mustache.php is a bit dangerous (see feature/higher-order-sections or 60d593dcabcd4e82c320bab1bfde622cb26aec8a).

    "Higher-order sections" is a feature of Mustache that allows template manipulation or pre-processing. If the tag referenced by a section returns a function, this function will be called and passed the body of the section. Whatever the function returns will replace the body of the section. See the 'lambdas' section here for examples.

    This works great in Ruby and Python, but can have unexpected side effects in PHP. The current implementation assumes that anything 'callable' should be treated as a higher-order function. Consider the following:

    class Monster extends Mustache {
        public $_template = '{{#title}}{{title}} {{/title}}{{name}}';
        public $title;
        public $name;
    $frank = new Monster();
    $frank->title = 'Dr.';
    $frank->name  = 'Frankenstein';
    $dracula = new Monster();
    $dracula->title = 'Count';
    $dracula->name  = 'Dracula';

    The first monster renders as Dr. Frankenstein, just as one would expect. But the second monster renders as 1Dracula since, according to PHP, the string 'Count' is a valid callback for count(). This is not desirable.

    I see a couple of options:

    1. Only allow PHP 5.3+ anonymous functions for higher-order sections. This keeps us from executing unintentional callbacks, but leaves all the poor PHP 5.2 folks out of the fun.
    2. Only allow anonymous functions or class-based callbacks for higher-order sections. i.e. array($this, 'myCallback') is a valid class-based callback, as are array('SomeClass', 'myCallback') and 'SomeClass::myCallback' ... 'count', however, is not.
    3. Keep the current implementation and let the buyer beware. This seems like a bad idea, so I'd suggest not voting for number 3.
    opened by bobthecow 17
  • Indentations are not correct

    Indentations are not correct


    There seems to be an issue with indentation when the depth of nested partials.

    For example:




    next line1


    next line2


        next line1
    next line2

    ruby implementation result

        next line1
        next line2
    opened by sgdot 0
  • 404 link in readme

    404 link in readme

    the readme is linking, at the bottom, to "mustache(5) man page." with link to https://mustache.github.com/mustache.5.html which is a 404. The real url should be : https://mustache.github.io/mustache.5.html

    opened by vincib 0
  • Update README.md

    Update README.md

    Fix mustache home page link.

    opened by samizdam 0
  • The right/best way to deal with newlines

    The right/best way to deal with newlines

    I'm pretty new at Mustache, so I might just have misunderstood, but it seems quite challenging to deal with user supplied text containing newlines.

    I was somewhat surprised to find that Mustache by default performs html encoding/escaping, but not nl2br. I then thought I would simply pass my string as nl2br, but obviously that will result in the
    s getting escaped themselves. Of course I could use {{{var}}} but then I lose my added security. I then looked into filters but found that $m->addHelper('nl2br', function($value) { return nl2br($value); } ); with {{var | nl2br}} would still result in escaped
    . Finally I found and adapted #173 and that worked.

    Now my main question is whether using $m->addHelper('nl2br', function($text, $mustache) { return nl2br($mustache->render($text)); } ); with {{#nl2br}}{{var}}{{/nl2br}} is indeed the best, cleanest and most correct option.

    I was also wondering, whether the answer is that that is the best option or not, if such a case shouldn't be mentioned in the wiki documentation. I looked around quite a bit specifically for this newline situation, since I presumed most mustache.php users would come across it, before moving on to trying to write a filter myself.

    opened by bertvandepoel 0
  • PHP 8.1 compatibility

    PHP 8.1 compatibility


    I just noticed some PHP 8.1 notices related to Mustache for a repo where this package is a dependency of a dependency ;-)

    While I'd love to send in some PRs to fix things, but that would require to first get the tests running on PHP 8.1.

    Looking at the current setup, I see the following issues:

    • CI still on Travis, while Travis is effectively dead for open source. 👉🏻 Would a PR to switch the existing Travis script over to GH Actions be welcome ?
    • PHPUnit limited to "~3.7|~4.0|~5.0". Making the tests PHP/PHPUnit cross version compatible to include PHP 8.x with those version constraints is going to be exceedingly hard. There is a PHPUnit Polyfills package available which will allow an upgrade to the tests to use PHPUnit 9.x assertions and expectations and get round the PHPUnit 8.x void issue, while still being able to run the tests all the way back to PHPUnit 4.x, but that package requires a minimum PHP version of PHP 5.4, while this package still requires PHP 5.2.

    I'd love some guidance on how to proceed.

    opened by jrfnl 2
  • get constant from the context when $id not found

    get constant from the context when $id not found

    Hello I would like the find method in context to return a constant when $id is not found. How can i override the search method in context?

    opened by astar86 0
  • How to escape {{ }}

    How to escape {{ }}

    Is there some way of passing through the curly braces literally? I'm using mustache in conjunction with Vue which also uses the mustache syntax so I'd like to selectively pass them through unprocessed.

    opened by thepurpleblob 3
  • Template containing html is loaded as empty

    Template containing html is loaded as empty

    I'm having a strange problem with one of the many templates I'm using.

    The bottom line is that the template and the array I pass to the render function results in an empty string.

    I inserted a couple of debug statement in the FilesystemLoader.php script in the load function to display the the content of $this->templates[$name] and I can see that an empty string is loaded instead of the template contents. The $name parameter contains the correct file name. No errors are returned by Mustache.

    If I delete the file, I get a Mustache error that the template can't be found so I'm requesting the correct template.

    The name of the template file is "users_table", it has the normal .mustache suffix and is in the correct template directory. I've attached it below. users_table.mustache.zip

    I'm at a loss to figure out what's causing this problem so grateful for any suggestions.


    opened by lcsqlpete 5
  • HTML Minify cache template

    HTML Minify cache template

    How about make minify cache template how like this https://github.com/jenstornell/tiny-html-minifier possible?

    opened by dejurin 5
  • FILTERS pragma for template loaders?

    FILTERS pragma for template loaders?


    I am just wondering if you've already thought about FILTERS for templates that would work the same way like for rendering values.

    Filter would look like like this: "stripcomments" => function($content) {return preg_replace('/<!--(.*)-->/Uis', '', $content)}

    opened by mxdpeep 2
  • v2.13.0(Nov 23, 2019)

    • Fix notices on PHP 7.4 (Thanks @tomjn, @stronk7, and @JoyceBabu!)
    • Fix a parse error in the delimiter change tag (e.g. {{=<% %>=}}) and throw a syntax error when it's invalid.
    • Improve Tokenizer::scan performance by 98.2%.
    • Test against all the PHPs in CI.
    Source code(tar.gz)
    Source code(zip)
  • v2.12.0(Jul 11, 2017)

    • Prevent redundant Autoloader registration (Thanks @hcpss-banderson!)
    • Add a ProductionFilesystemLoader, which doesn't read template file contents before every render.
    • Improve test coverage.
    • Fix a bug when rendering the same block names multiple times in one template.
    • Add a delimiters option for overriding default delimiters at the engine level.
    • Add validation to prevent empty template_class_prefix config.
    Source code(tar.gz)
    Source code(zip)
  • v2.11.1(Jul 31, 2016)

  • v2.11.0(Jul 31, 2016)

    • Add support for exception chaining (Thanks @thewilkybarkid!)
    • Support parent tags and block args as direct children of blocks and sections.
    • Add support for non-local templates via FilesystemLoader (Thanks @oschettler!)
    Source code(tar.gz)
    Source code(zip)
  • v2.10.0(Feb 27, 2016)

    • Respect delimiter changes inside lambda sections. See janl/mustache.js#489
    • Fix incorrect padding added to lambda values inside partials. See #286
    • Make LambdaHelper invokable. See #285
    Source code(tar.gz)
    Source code(zip)
  • v2.9.0(Aug 15, 2015)

    • Lazily evaluate template BLOCKS pragma sections. See #264 and #265. Thanks @damyon!
    • Add ANCHORED-DOT pragma to enable "anchored dot notation". See #129 and mustache/spec#52
    • A bit of CS cleanup, and remove the unused create_example script.
    Source code(tar.gz)
    Source code(zip)
  • v2.8.0(Apr 1, 2015)

  • v2.7.0(Aug 26, 2014)

    • Add template inheritance, via the BLOCKS pragma. Thanks @jazzdan and the rest of the @Etsy devs!
    • Add a pragmas option to the Mustache_Engine constructor for enabling default pragmas.
    • A couple of performance improvements. Thanks @nizsheanez!
    • Code cleanup. Thanks @keradus!
    • Check coding standards on CI. Thanks @keradus!
    • Fix whitespace bug in nested partials. Thanks for the bug report, @mikesherov and @behance!
    • Allow omitting the filters on closing section tags, for example, {{# a | b }}{{/ a }} is now valid.
    • Increase test coverage, improve comments and examples.

    If you process Mustache parse trees yourself…

    Note that the parse tree representation of filtered interpolation and section tokens has changed. The tag name is now separate from the filters list. For example, the template:

    {{ foo | bar }}

    was parsed as:

        "type" => "%",
        "name" => "FILTERS",
        "line" => 0
        "type"  => "_v",
        "name"  => "foo | bar | baz",
        "otag"  => "{{",
        "ctag"  => "}}",
        "line"  => 0,
        "index" => 33

    but is now parsed as:

        "type" => "%",
        "name" => "FILTERS",
        "line" => 0
        "type"    => "_v",
        "name"    => "foo",
        "otag"    => "{{",
        "ctag"    => "}}",
        "line"    => 0,
        "index"   => 33,
        "filters" => [
    Source code(tar.gz)
    Source code(zip)
  • v2.6.0(Jun 20, 2014)

    Lots of little changes, plus two bigger ones:

    • Fix disabling lambda template cache option: it didn't before, now it does.
    • Improve tokenizer performance: 25-60% performance boost!
    Source code(tar.gz)
    Source code(zip)
  • v2.6.1(Jun 20, 2014)

  • v2.5.1(Feb 28, 2014)

  • v2.5.0(Dec 14, 2013)

    • Add section filter support
    • Add more flexible cache options (thanks @amitsnyderman!)
    • A nested partials whitespace bugfix
    • Add ArrayAccess context lookup support (thanks @kriss0r!)
    • Some lambda section optimizations and smarter lambda cache defaults
    Source code(tar.gz)
    Source code(zip)
  • v2.4.1(Aug 13, 2013)

    • Fix autoloader for paths starting with ./ (thanks @mirkolofio!)
    • Allow stream URIs in Filesystem Loader (thanks @mlebrun!)
    • Fix bonus indents in lambda sections inside indented partials
    Source code(tar.gz)
    Source code(zip)
A complete and fully-functional implementation of the Jade template language for PHP

Tale Jade for PHP Finally a fully-functional, complete and clean port of the Jade language to PHP — Abraham Lincoln The Tale Jade Template Engine brin

Talesoft 93 May 4, 2021
PHP template engine for native PHP templates

FOIL PHP template engine, for PHP templates. Foil brings all the flexibility and power of modern template engines to native PHP templates. Write simpl

Foil PHP 163 Nov 20, 2021
Twig, the flexible, fast, and secure template language for PHP

Twig, the flexible, fast, and secure template language for PHP Twig is a template language for PHP, released under the new BSD license (code and docum

Twig 7.3k Nov 24, 2021
Smarty is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic.

Smarty 3 template engine smarty.net Documentation For documentation see www.smarty.net/docs/en/ Requirements Smarty can be run with PHP 5.2 to PHP 7.4

Smarty PHP Template Engine 1.9k Nov 23, 2021
Native PHP template system

Plates Plates is a native PHP template system that's fast, easy to use and easy to extend. It's inspired by the excellent Twig template engine and str

The League of Extraordinary Packages 1.3k Nov 19, 2021
☕ Latte: the intuitive and fast template engine for those who want the most secure PHP sites.

Latte: amazing template engine for PHP Introduction Latte is a template engine for PHP which eases your work and ensures the output is protected again

Nette Foundation 731 Nov 27, 2021
Multi target HAML (HAML for PHP, Twig, )

Multi target HAML MtHaml is a PHP implementation of the HAML language which can target multiple languages. Currently supported targets are PHP and Twi

Arnaud Le Blanc 362 Aug 5, 2021
PHP Template Attribute Language — template engine for XSS-proof well-formed XHTML and HTML5 pages

PHPTAL - Template Attribute Language for PHP Requirements If you want to use the builtin internationalisation system (I18N), the php-gettext extension

PHPTAL 165 Nov 17, 2021
View template engine of PHP extracted from Laravel

Blade 【简体中文】 This is a view templating engine which is extracted from Laravel. It's independent without relying on Laravel's Container or any others.

刘小乐 145 Aug 13, 2021
Provides TemplateView and TwoStepView using PHP as the templating language, with support for partials, sections, and helpers.

Aura View This package provides an implementation of the TemplateView and TwoStepView patterns using PHP itself as the templating language. It support

Aura for PHP 81 Nov 16, 2021
TextGenerator is a PHP package that aims to generate automated texts from data.

TextGenerator TextGenerator is a PHP package that aims to generate automated texts from data. Feel free to comment and contribute. Features Text gener

Vincent Brouté 85 Jul 19, 2021
A faster, safer templating library for PHP

Brainy Brainy is a replacement for the popular Smarty templating language. It is a fork from the Smarty 3 trunk. Brainy is still very new and it's lik

Box 64 Jan 15, 2021
A ready-to-use Model View Controller template in PHP

PHP-MVC-Template A ready-to-use Model View Controller template in PHP Use this repo as a template! (Or clone it) Start to configure your MVC file Afte

Loule | Louis 6 Nov 19, 2021
Derste birlikte hazırladığımız PHP Tema Motoru kaynak kodları

Prototürk Template Engine Prototürk'de sorulan bir soru üzerine videoda birlikte hazırladığımız php ile geliştirilmiş basit bir tema motoru. Geçerli d

Tayfun Erbilen 12 Nov 1, 2021
Provides a GitHub repository template for a PHP package, using GitHub actions.

php-package-template Installation ?? This is a great place for showing how to install the package, see below: Run $ composer require ergebnis/php-pack

null 260 Nov 24, 2021
The free-to-use template for your Imagehost-website made with PHP, HTML and CSS!

The free-to-use template for your Imagehost-website made with PHP, HTML and CSS! Some information before we start This repo is only code related, to a

Ilian 5 Nov 3, 2021
Qiq templates for PHP 8.

Qiq Templates for PHP 8 This package provides a PHP 8.0 implementation of the TemplateView and TwoStepView patterns using PHP itself as the templating

null 10 Nov 9, 2021
Standalone Skeltch templating engine for PHP

SkeltchGo is a standalone version of Glowie Skeltch templating engine for PHP, intented to use from outside the framework.

glowie 1 Nov 5, 2021
The free-to-use template for your Imagehost-website made with PHP, HTML and CSS!

The free-to-use template for your Imagehost-website made with PHP, HTML and CSS! Some information before we start This repo is only code related, to a

Ilian 5 Nov 3, 2021