Let’s say that you want to create a website.  Maybe it will be a casino website like Vegas casino online or maybe it will be a website about Pokemon cards.  But whatever your final website becomes, in all likelihood, you will store the data in a database and display the data on the website.  Either you can do that with raw code, or you can use a templating system.  One option for a templating system is Mustache.

What are the top templating choices for HTML and PHP?

  1. Twig, which is used by Drupal (Content Management System).
  2. Smarty, used by phpBB (bulletin board system) and Mahara (electronic portfolio system).
  3. Mustache, used by Moodle (online educational system).

Why do developers choose the mustache template system over other template systems?

There are several reasons why developers may choose the Mustache Template System over other template systems.

It is very simple to use, and it is easy to read even for non technical people.  Mustache follows a “logic-less” approach, which means it has a minimal set of control structures. This simplicity makes it easy to learn, use, and understand. Developers appreciate its straightforward syntax, which makes it accessible to both technical and non-technical team members.

Mustache is very portable.  It is accessible within multiple programming languages, not just PHP.  he same template can be used across different platforms, reducing duplication of effort and maintaining consistency.

Mustache helps to maintain a clear separation between data and presentation, but that can be said about almost any templating system.  That is why programmers choose to use a templating system.

Mustache provides flexibility.  It can be used in various scenarios, from simple static templates to dynamic, data driven templates.  It can adapt to different use cases, making it a versatile option for different types of projects.  But again, that can be said for a majority of template systems.

Mustache is very easy to test.  Developers can verify that the data is being displayed correctly without dealing with complex logic in the templates.

With its logic-less design, Mustache reduces the risk of security vulnerabilities such as code injection or template manipulation.

What programming languages does Mustache work with?

Available in the following programming languages (and environments)

ABAP, ASP, ActionScript, Android, Bash,
C, C#/.NET, C++, CFEngine,
Clojure, Clojure[Script], CoffeeScript,
ColdFusion, Common Lisp, Crystal,
D, Dart, Delphi, Elixir, Elm,
Erlang, Fantom, Go, Haskell, Haxe,
Io, Java, JavaScript, Julia,
Kotlin, Lua (used by MediaWiki), Nim,
OCaml, Objective-C, Ooc (Object Oriented C),
PHP, Perl, Pharo, Python,
R, Racket, Raku, Ruby, Rust,
Scala, SQL (SQL Server), Swift,
Tcl, XQuery

What are the different tag types in Mustache?

The Mustache documentation talks about “template”, “hash”, and “output”.

The “output” is the most obvious.  It is the text that is finally displayed to the end user.

The “template” is the text file that template for how the “output” will be displayed.  For example,

The quick {{color}} {{animal}} jumps over the lazy {{animal2}}.

Depending on what {{color}}, {{animal}}, and {{animal2}} are set to, we could get the following sentences:

  1. The quick brown fox jumps over the lazy dog.
  2. The quick white dog jumps over the lazy fox.
  3. The quick gray elephant jumps over the lazy mouse.

Hash is the most complicated item.  It is part that is stored in the source code (all of those programming languages that I listed above).  But they all follow a similar format, even if the individual programming language does not have something called “hash”.

In Mustache templating, a hash refers to an object or a dictionary-like data structure that contains key-value pairs. In JavaScript, this data structure is often represented as an object, while in other programming languages, it may be called a dictionary, associative array, or map.

In the context of Mustache templates, hashes are used to provide dynamic data to the template engine. When rendering a Mustache template, you can pass a hash as the data context, and then the template can access and use the values associated with the keys in the hash.

For example, if your template file, “frontpage.mustache”, contains the following code and your programming language is JavaScript:

Hello, {{name}}! Your age is {{age}}.

Your hash will be of the following format:

const template = “frontpage.mustache”

const data = {

    name: “John Doe”,

    age: 30,

};

const renderedTemplate = Mustache.render(template, data);

console.log(renderedTemplate);

The “output” (what is shown on the webpage to the end user) would be

Hello, John Doe! Your age is 30.

It is that simple.  Yea, right … once we start to talk about sections, include this section, do not include that section, etc. it becomes a little bit more complicated.  Not to mention arrays of data are to be repeated.

Variables

The most basic tag type is the variable. A {{name}} tag in a basic template will try to find the name key in the current context. If there is no name key, the parent contexts will be checked recursively. If the top context is reached and the name key is still not found, nothing will be rendered.

We saw how this worked in the previous section, so I do not need to repeat it here.

Sections (in general)

Sections render blocks of text one or more times, depending on the value of the key in the current context.

A section begins with a pound and ends with a slash. That is, {{#person}} begins a “person” section while {{/person}} ends it.

The behavior of the section is determined by the value of the key.

{{#person}}
The world is awesome!
{{/person}}

As long as there is a value for “person” that is not false, the text “The world is awesome!” will always be displayed.

Sections False Values or Empty Lists

What happens when the value of our variable is false or it is an empty list?

Shown.

{{#person}}

Never shown!

{{/person}}

If “person” is “false”, then the text “Never shown!” is not displayed.

Sections Non-Empty Lists

When the value is a non-empty list, the text in the block will be displayed once for each item in the list. The context of the block will be set to the current item for each iteration. In this way we can loop over collections.

{{#repo}}
<b>{{name}}</b>
{{/repo}}

If there are three items in our list (chicken, beef, turkey), our “output” will be:

<b>chicken</b>
<b>beef</b>
<b>turkey</b>

Section Lambdas (functions)

When the value is a callable object, such as a function or lambda, the object will be invoked and passed the block of text. The text passed is the literal block, unrendered. {{tags}} will not have been expanded – the lambda should do that on its own. In this way you can implement filters or caching.

This is more complicated than this article can explain, so you will have to do additional research for realistic examples.

Section Non False Values

When the value is non-false but not a list, it will be used as the context for a single rendering of the block.

That makes sense.  You have a single item, you want it to be displayed as if you had a list with only one item in it.  But you do not have to declare a list with a single item.  You can just pass the regular variable and Mustache will handle things appropriately.

A Section that is Inverted

An inverted section begins with a caret (hat) and ends with a slash. That is {{^person}} begins a “person” inverted section while {{/person}} ends it.

While sections can be used to render text one or more times based on the value of the key, inverted sections may render text once based on the inverse value of the key. That is, they will be rendered if the key doesn’t exist, is false, or is an empty list.

{{#repo}}
<b>{{name}}</b>
{{/repo}}
{{^repo}}
You really messed up your data, didn’t you 🙁
{{/repo}}

Comments

Comments begin with a bang and are ignored.

<h1>Today{{! ignore me }}.</h1>

The output will be:

<h1>Today.</h1>

Comments may contain newlines.

Partials

Partials begin with a greater than sign, like {{> box}}.

Partials are rendered at runtime (as opposed to compile time), so recursive partials are possible.  This is true even for languages that are not compile languages.

{{> next_more}}

The next_more.mustache file will inherit the size and start methods from the calling context.

You may want to think of partials as includes, imports, template expansion, nested templates, or subtemplates, even though those aren’t literally the case here.

Here is an example:

base.mustache:

<h2>Names</h2>

{{#names}}

{{> user}}

{{/names}}

user.mustache:

<strong>{{name}}</strong>

But it can be thought of as this:

<h2>Names</h2>

{{#names}}

<strong>{{name}}</strong>

{{/names}}

Summary

Mustache is a very power templating system, and once you get started working with templates, you will never go back to traditional HTML output creation.