PHPackages                             phly/mustache - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. phly/mustache

Abandoned → [phly/phly-mustache](/?search=phly%2Fphly-mustache)ArchivedLibrary[Templating &amp; Views](/categories/templating)

phly/mustache
=============

PHP 5.3 Mustache Implementation

1.2.2(10y ago)12111.6k11[1 issues](https://github.com/phly/phly_mustache/issues)6BSD-3-ClausePHPPHP &gt;=5.3.3

Since Mar 14Pushed 10y ago1 watchersCompare

[ Source](https://github.com/phly/phly_mustache)[ Packagist](https://packagist.org/packages/phly/mustache)[ Docs](http://weierophinney.github.com/phly_mustache/)[ RSS](/packages/phly-mustache/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (1)Versions (9)Used By (6)

Phly\\Mustache
==============

[](#phlymustache)

> # MOVED!
>
> [](#moved)
>
> This package has moved to [phly/phly-mustache](https://github.com/phly/phly-mustache), and the package name has changed to `phly/phly-mustache`.
>
> I have updated packagist to mark `phly/mustache` as abandoned and to point users to the new package name. All previous releases are available under the old package name, and have the same functionality. The new package contains the v2 code, however, which has never been released under the old name.

Phly\\Mustache is a Mustache () implementation written for PHP 5.3+. It conforms to the principles of mustache, and allows for extension of the format via pragmas.

For full documentation, please visit [ReadTheDocs](http://phly-mustache.readthedocs.org/).

The mailing list is at [https://groups.google.com/d/forum/phly\_mustache](https://groups.google.com/d/forum/phly_mustache)

At this time, Phly\\Mustache has support for the following:

- `PhlyTest\Mustache\Mustache`

    - Renders string templates
    - Renders file templates
    - Can use object properties for substitutions
    - Can use method return value for substitutions
    - Template may use conditionals
    - Conditional is skipped if value is false
    - Conditional is skipped if value is empty
    - Template iterates arrays
    - Template iterates traversable objects
    - Higher order sections render inside out
    - Template will dereference nested arrays
    - Template will dereference nested objects
    - Inverted sections render on empty values
    - Renders partials
    - Allows aliasing partials
    - Escapes standard characters
    - Triple mustaches prevent escaping
    - Honors implicit iterator pragma
    - Allows setting alternate template suffix
    - Strips comments from rendered output
    - Allows specifying alternate delimiters
    - Alternate delimiters set in section only apply to that section
    - Alternate delimiters apply to child sections
    - Alternate delimiters do not carry to partials
    - Pragmas are section specific
    - Pragmas do not extend to partials
    - Handles recursive partials
    - Lexer strips unwanted whitespace from tokens
    - Array values that refer to p h p built ins should not call them
    - Object properties that refer to p h p built ins should not call them
    - Array values that refer to static methods should not call them
    - String values that refer to functions should not call them
    - Array values that refer to static methods in array syntax should not call them
    - Std class as view should not raise error
    - Dot notation is exanded to sub property of view
    - With dot notation if subproperty does not exist empty string is rendered
- `PhlyTest\Mustache\HierarchicalViews`

    - Understands hierarchical templates
    - Placeholders are rendered as unnamed sections
    - Only placeholders with replacements receive substitutions
    - Can render multiple placeholders
    - Can render nested child placeholders
    - Nested children can render placeholders defined in parent child
- `PhlyTest\Mustache\DefaultResolver`

    - Resolves using mustache suffix by default
    - Resolves using provided suffix
    - Resolves using specified directory separator
    - Uses path stack internally
- `PhlyTest\Mustache\Pragma\SubViews`

    - Sub view content is captured in parent
    - Renders nested sub views
    - Sub view uses parent view when no view provided
    - Should render sub view returned by closure
    - Std class composing sub view should not raise error

Architecture
============

[](#architecture)

Phly\\Mustache consists of five primary classes:

- Lexer: tokenizes mustache syntax.
- Renderer: renders a list of tokens, using substitions provided via a view.
- Pragma: interface for pragmas, which may modify how tokens are handled
- Resolver: resolves a template name to mustache syntax or tokens.
- Mustache: facade/gateway class. Tokenizes and renders templates, caches tokens, provides partial aliasing, and acts as primary interface for end-users.

Usage
=====

[](#usage)

Usage is fairly straightforward:

```
include '/path/to/library/Phly/Mustache/_autoload.php';
use Phly\Mustache\Mustache;

$mustache = new Mustache();
echo $mustache->render('some-template', $view);

```

By default, phly\_mustache will look under the current directory for templates ending with '.mustache'; you can create a stack of directories to search by using the setTemplatePath() method:

```
$mustache->setTemplatePath($path1)
         ->setTemplatePath($path2);

```

In the above, it will search first $path2, then $path1 to resolve the template.

You may also change the suffix it will use to resolve templates:

```
$mustache->setSuffix('html'); // use '.html' as the suffix

```

If your templates use pragmas, you must first add pragma handlers to the renderer. This can be done as follows:

```
use Phly\Mustache\Pragma\ImplicitIterator as ImplicitIteratorPragma;
$mustache->getRenderer()->addPragma(new ImplicitIteratorPragma());
$mustache->render('template-with-pragma', $view);

```

Views can be either associative arrays or objects. For objects, any public member, either a property or a method, may be referenced in your template. As an example:

```
class View
{
    public $first_name = 'Matthew';

    public $last_name  = "Weier O'Phinney";

    public function full_name()
    {
        return $this->first_name . ' ' . $this->last_name;
    }
}

```

Any property (or array key) may also refer to a valid callback; in such cases, the return value of the callback will be used.

```
$view = new \stdClass;
$view->first_name = 'Matthew';
$view->last_name  = "Weier O'Phinney";
$view->full_name  = function() use ($view) {
    return $view->first_name . ' ' . $view->last_name;
};

```

The following sections detail unique and/or advanced features of phly\_mustache.

Autoloading
===========

[](#autoloading)

phly\_mustache follows the PSR-0 standard for class naming conventions, meaning any PSR-0-compliant class loader will work. To simplify things out of the box, the component contains an "\_autoload.php" file which will register an autoloader for the phly\_mustache component with spl\_autoload. You can simply include that file, and start using phly\_mustache.

Higher Order Sections
=====================

[](#higher-order-sections)

"Higher order sections" refer to callbacks that return callbacks. As an example, consider the following template:

```
{{#bolder}}Hi {{name}}.{{/bolder}}

```

and the following view:

```
$view = new \stdClass;
$view->name = 'Tater';
$view->bolder = function() {
    return function($text, $renderer) {
        return '' . $renderer($text) . '';
    };
};

```

In this case, the contents of the section, "Hi {{name}}." will be passed as the first argument to the section, and a callback capable of rendering will be passed as the second (this is basically a closure that curries in the current Renderer object and calls the appropriate method). This allows you to re-use a given "section" in order to create re-usable capabilities; think of them like "view helpers" in systems like Zend\_View, Solar\_View, Savant, etc.

Partials
========

[](#partials)

Partials are a basic form of inclusion within Mustache; anytime you find you have re-usable bits of templates, move them into a partial, and refer to the partial from the parent template.

Typically, you will only reference partials within your templates, using standard syntax:

```
{{>partial-name}}

```

However, you may optionally pass a list of partials when rendering. When you do so, the list should be a set of alias/template pairs:

```
$mustache->render($template, array(), array(
    'winnings' => 'user-winnings',
));

```

In the above example, 'winnings' refers to the template "user-winnings.mustache". Thus, within the $template being rendered, you may refer to the following partial:

```
{{>winnings}}

```

and it will resolve to the appropriate aliased template.

A few things to remember when using partials:

- The parent template may change tag delimiters, but if you want to use the same delimiters in your partial, you will need to make the same declaration.
- The parent template may utilize one or more pragmas, but those declarations will not perist to the partial; if you want those pragmas, you must reference them in your partial.

Basically, partials render in their own scope. If you remember that one rule, you should have no problems.

Hierarchical Views and Placeholders
===================================

[](#hierarchical-views-and-placeholders)

(Available in versions 1.1.0 and up).

Placeholders are basically unnamed sections, and are denoted by the combination of `{{$name}}` and `{{/name}}`. When encountered by the renderer, any mustache content within will be rendered as normal mustache content.

Placeholders are primarily of use with the concept of hierarchical views. These are denoted by the combination of `{{
