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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • hogan.js style template inheritance

    hogan.js style template inheritance

    Modeled after hogan.js, with functional tests for template inheritance copied from the hogan.js test suite.

    An additional test I performed was modifying the mustache/spec to have these same template inheritance rules. I then successfully ran the test suites of mustache.php with this patch and the most recent version of hogan.js after pointing them both at my modified mustache spec. It appears that they are both 100% compatible with one another.

    This wasn't a solo effort by any means. Much thanks to my coworkers @dtb, @mdg and @benburry at @Etsy.

    opened by jazzdan 15
  • Lazily evaluate blocks pragmas.

    Lazily evaluate blocks pragmas.

    Patch for issue #264.

    The unit tests are unmodified and all passing - the new unit tests cover the exact use case documented on the blocks pragma page, and include an additional test for whitespace conformance.

    With regards to the solution, I originally tried using a lambahelper to reparse the source - but hit whitespace issues because there is logic in the tokeniser about removing whitespace for standalone tags etc. This solution creates an anonymous function to defer the execution of the generated code.

    opened by damyon 14
  • Framework Integrations

    Framework Integrations

    I did stumble over https://github.com/bobthecow/mustache.php/wiki/Framework-integration

    With the first release of my template abstraction: https://github.com/schranz-templating/templating/releases/tag/0.1.0

    The mustache php package can be used in current version of Symfony, Laravel, Spiral, Laminas and Mezzio.

    List of packages: https://packagist.org/?query=schranz-templating%20mustache

    opened by alexander-schranz 0
  • Partial with a possible argument

    Partial with a possible argument

    I've started implementing Moustache in a sample project to see if it would help me with flexibility when it comes to templates.

    I have a file called top.php that has the following:

    <div id="top">
       {{> navigation }}

    Navigation in PHP is an array as there can be multiple navigations, it would look like this:

    $data = [
      "navigation" => [
        "main" => HTML_HERE,
        "left" => HTML_HERE

    How can I make it configurable to only render "main" or "left"? I tried the following:

    <div id="top">
      {{> #navigation }}
        {{ main }}
      {{> /navigation }}

    And then I have the navigation partial:

    <div class="navigation">
      {{ }}

    but I'm not sure how to get it to work. The navigation.moustache should be a reusable HTML but I only want to display one at the time. This is an example html I would like:

    <div id="top">
      <div class="navigation">
    <div id="content">
        <div class="navigation">
    opened by moseleyi 0
  • Dubugging template rendering

    Dubugging template rendering

    I have the same problem described here: https://stackoverflow.com/questions/24866030/mustache-php-debugging Template waits a string, so accidentally passing an array causes a nightmare of debugging.

    I am throw an exception inside of 'escape' to understand in which template file the problem occurs, but I still can't figure out which {{variable}} received an array.

    Do we have some way to resolve this problem? I scanned source code, but couldn't find any API for this.

    opened by devope 0
  • Bump to PHPUnit 9

    Bump to PHPUnit 9

    Running tests of Mustache.php on a PHP 8.1 environment requires to bump PHPUnit to a recent version.

    • Configuration file has been updated with phpunit --migrate-configuration
    • PHPUnit_Framework_TestCase is replaced by \PHPUnit\Framework\TestCase
    • assertContains is replaced by assertStringContainsString
    • @expectedException annotation is replaced by $this->expectException
    • setUp() and setUpBeforeClass() should match parent implementation

    Note: $this-assertTrue(true); has been added to avoid risky tests (tests without assertions).

    friendsofphp/php-cs-fixer has also been bumped to its latest version during the update process.

    opened by nterray 0
  • Add option to disable lambda rendering

    Add option to disable lambda rendering

    This pull request adds an option called disable_lambda_rendering that can be used to disable rendering of lambda return values. This is necessary to prevent repeated rendering if the lambda already takes care of rendering its own content.

    opened by larsbonczek 0
  • v2.14.2(Aug 23, 2022)

  • v2.14.1(Jan 21, 2022)

    • Fix CVE-2022-0323, possible RCE when rendering untrusted user templates, reported by @altm4n via huntr.dev
    • Improve compatibility with PHP 8.1
    Source code(tar.gz)
    Source code(zip)
  • v2.14.0(Dec 14, 2021)

    • Improve compatibility with PHP 8.1 (thanks @schlessera!)
    • Update spec to v1.2.2
    • Various README and CONTRIBUTORS updates (thanks @samizdam and @Kirill89!)
    • Add .gitattributes for better release packaging (thanks @fezfez!)
    Source code(tar.gz)
    Source code(zip)
  • 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.1(Jun 20, 2014)

  • 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.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 91 Dec 27, 2022
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 167 Dec 3, 2022
A PHP project template with PHP 8.1, Laminas Framework and Doctrine

A PHP project template with PHP 8.1, Laminas Framework and Doctrine

Henrik Thesing 3 Mar 8, 2022
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.7k Jan 1, 2023
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 2.1k Jan 1, 2023
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 Jan 7, 2023
☕ 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 898 Dec 25, 2022
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 363 Nov 21, 2022
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 175 Dec 13, 2022
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.

刘小乐 143 Dec 13, 2022
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 83 Jan 3, 2023
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é 89 Dec 26, 2022
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 66 Jan 3, 2023
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 20 Dec 26, 2022
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 20 Nov 9, 2022
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 280 Dec 27, 2022
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 6 Jul 22, 2022
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 18 Nov 24, 2022
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