phly_mustache

PHP 5.3 Mustache implementation


Project maintained by weierophinney Hosted on GitHub Pages — Theme by mattgraham

Phly\Mustache is a Mustache (http://mustache.github.com) implementation written for PHP 5.3+. It conforms to the principles of mustache, and allows for extension of the format via pragmas. Additionally, it supports hierarchical templates, providing a unique and elegant solution to layouts.

Getting Started

Installation

Use the links at the top of this page to download and install phly_mustache. Alternately, you can use Composer. Simply add an entry to your composer.json:


{
    "require": {
        "phly/mustache": "1.*"
    }
}

and then execute:


$ php composer.phar install

or:


$ php composer.phar update

Documentation

Getting Help

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.

For full syntax and usage examples, read the documentation.