Blog

This blog is usually for boring…technical detail. For more interesting post, go checkout my linkedIn post!

It’s a template system used by openapi generator. It is a logic-less program where control like “if”, “else” or “for” does not exist. Its control is entirely dependent on data structure you feed into mustache.

Basic

suppose we have mustache file as follows

Hello {{name}}

Data

{ "name": "Alice" }

Then output is

Hello Alice!

by default, {{variable}} will html-escape value. For example, if we have

{ "name": "Alice <bob@example.com>" }

we get

Hello My &quot;quoted&quot; api!

However, if you use three curly braces for the same data

Hello {{{name}}}

you will get raw value

Hello My "quoted" api!

suppose we have mustache file as follows

Hello {{name}}

Data

{ "name": "Alice" }

Then output is

Hello Alice!

by default, {{variable}} will html-escape value. For example, if we have

{ "name": "Alice <bob@example.com>" }

we get

Hello My &quot;quoted&quot; api!

However, if you use three curly braces for the same data

Hello {{{name}}}

you will get raw value

Hello My "quoted" api!

Section

Section is multi-purpose block that starts with # and end with / which behave differently depending on the value.

Conditional Value

if the value is boolean true, the section is rendered. If it’s false, it’s ignored.

eg:

{{#isAdmin}}
Welcome to the admin panel!
{{/isAdmin}}

Loop

if the item is the list, it behave like foreach. The context change to the current item in the loop. template:

{{#items}}
* {{name}}
{{/items}}

Data:

{
"items": [
{ "name": "Item A" },
{ "name": "Item B" }
]
}

output:

* Item A
* Item B

Inverted Section

It starts with ^, and it renders only if the value is false, empty list, null. It act as an else block.

{{#showWarning}}
Warning! Something is wrong.
{{/showWarning}}
{{^showWarning}}
All systems normal.
{{/showWarning}}

Partial

it starts with > (greater than), and it’s functionally similar to #include, template file in partial name will be copy-pasted.

eg:

{{> partial_name }}

This loads and inserts the content of the template file named partial_name.mustache.

Lambdas

Triggered when the value of section is function. And function is executed using the text inside that section.

eg:

template

{{#uppercase}}
{{name}} is awesome!
{{/uppercase}}

data:

const data = {
name: "brian",
uppercase: function() {
return function(text, render) {
return render(text).toUpperCase();
}
}
};

output:

BRIAN IS AWESOME!

Custom Delimiter

By default, mustache use curly braces. But you can use other delimiter. Such as [[var]] or <%var%>.

To use custom delimiter, you use = inside current delimiter. For example,

{{=<% %>=}}

this will use <%var%> instead of {{var}}.

Posted in ,

Leave a comment