Mustache Templates in PHP

I’ve always admired the simplicity of Mustache templates but the complication of internationalization support has always prevented me using them until a recent project. I used them in my Magic: the Gathering tournament software.

Mustache templates look like this:

<h2>Create Event</h2>

<form action="{{formAction}}" method="post">
  <label for="format">Format</label> <input type="text" name="format">
  <label for="cost">Cost</label> <input type="text" name="cost">
  <input class="btn btn-primary btn-block" type="submit">
</form>

You can see a bunch from the project at https://github.com/bakert/tournament/tree/master/views.

As long as you have { "require": { "mustache/mustache": "~2.5" } } in your composer.json using them is as simple as:

$loader = new Mustache_Loader_FilesystemLoader('path/to/templates');
$engine = new Mustache_Engine(['loader' => $loader]);
echo $engine->render('template_name', $arguments);

I wrapped this up in a class (Template) and a global (T()) so I could make calls like this:

echo T()->signin($args);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.