Templates are a great way to separate your website’s code from its design. There are many great web template systems available for different languages and platforms, including Smarty for PHP and the Django template language for Python.
In this tutorial, you’ll explore Mustache, a relatively new and very simple template system that you can easily use to create HTML templates. You’ll look at various topics, including:
- The advantages of using Mustache
- How to install and use the Mustache processor
- How Mustache tags, variables, and data objects work
- Using sections to create conditions and loops
- Including one Mustache template inside another
- …and lots more!
Along the way, you’ll see plenty of code examples that show you how Mustache works. At the end of the tutorial, there’s a complete example that uses Mustache, along with jQuery, to create a simple Ajax-based product list page.
What is Mustache?
Moustache is a simple template system that you can use when building websites and web apps. By using a template system, you can keep your back-end code separate from the markup that displays the front end to the user. This clean separation gives you many advantages. For example, it makes it easy for a designer to work on a website’s visual design without the risk of messing up the site’s code. It also makes it easy for you to change the design at a later point without impacting the back-end code.
One of Mustache’s big plus points is that is logic-less, which means it keeps your templates very neat and tidy. There are no messy or
if ... then looping constructs embedded within a Mustache template; it’s all just markup and simple Mustache tags. All the logic is hidden away inside your data objects (and the code that creates or fetches them).
The Mustache processor is available in a wide range of languages. As a general rule, you install Mustache like this:
- Click the ZIP button to download the repository Zip file.
- Unzip the downloaded file, and move the resulting folder to your website.
- Include the relevant library file (such as or
Mustache.php) in your web pages or server-side scripts.
Running the Mustache processor
The syntax for calling the Mustache processor depends on the language you are using. Essentially though, you call the class’s
Mustache or object’s method
render(), passing in the template string followed by the data object. The processor then combines the template with the data object to produce the final markup string, which it returns.