How to use the parse function from mustache

Find comprehensive JavaScript mustache.parse code examples handpicked from public code repositorys.

The mustache.parse function compiles a Mustache template string into an array of tokens that can be used to render the template with data.

234
235
236
237
238
239
240
241
242
243
server.views({
    engines: {
        html: {
            compile: (template) => {

                Mustache.parse(template);

                return (context) => {

                    return Mustache.render(template, context);
fork icon70
star icon194
watch icon19

76
77
78
79
80
81
82
83
84
85
86
function _interpolate(ctx, qa, s, encode) {
  const lookup = encode ?
    v => encodeURIComponent(getDynamicValue(ctx, qa, v)) :
    v => getDynamicValue(ctx, qa, v)


  return mustache.parse(s)
    .map(t => t[0] === 'name' ? lookup(t[1]) : t[1])
    .join('')
}

fork icon3
star icon2
watch icon6

How does mustache.parse work?

The mustache.parse function is a part of the Mustache templating library and it compiles a Mustache template string into an array of tokens that can be used to render the template with data. To accomplish this, the parse function first tokenizes the template string into a series of Mustache tokens such as {{, }}, #, ^, /, !, and text nodes, each of which represents a particular type of Mustache tag or content. Next, it parses these tokens to create a tree-like structure that represents the logical structure of the template, including any sections, inverted sections, partials, and plain text nodes. This tree structure is called an AST (Abstract Syntax Tree). Finally, the parse function returns the AST as an array of nodes that can be used by the Mustache library's rendering functions to render the template with data. By breaking down the template into tokens and constructing an AST, the parse function enables the Mustache library to efficiently render templates with dynamic data, without having to parse the template string every time the data changes.

Ai Example

1
2
3
4
5
6
7
8
9
10
11
const Mustache = require("mustache");

const template = `
{{title}}
{{#items}}
{{name}}: {{value}}
{{/items}}
`;

const tokens = Mustache.parse(template);
console.log(tokens);

In this example, we're using the Mustache library to compile a template string into an array of tokens using the parse method. We define a template string that includes Mustache tags for rendering dynamic data, and pass it to the parse method. The resulting tokens array contains each of the Mustache tags and text nodes as separate objects, and can be used to render the template with data using other Mustache library functions. When we run this code, it will output an array of tokens representing the Mustache template: yaml Copy code