Mustache.js - Logic-less Templates

4.2.0 · active · verified Sun Apr 19

Mustache.js is a zero-dependency, logic-less templating engine for JavaScript, faithfully implementing the Mustache template system. Its current stable version is 4.2.0, with releases primarily focusing on bug fixes and minor enhancements. The library enables developers to utilize tag-based templates for a wide array of outputs, including HTML, configuration files, and source code, by expanding tags with values provided from a JavaScript object or hash. A key differentiator is its strict adherence to a 'logic-less' philosophy, meaning it explicitly avoids traditional control flow statements (like `if/else` or `for` loops), rendering content solely based on the presence or absence of data and iterating over arrays without explicit loops. Mustache.js offers broad compatibility, supporting CommonJS, AMD, and ECMAScript Modules, making it suitable for modern web browsers, Node.js server-side environments, and even as a command-line tool.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic template rendering with a view object, rendering from a local file, and an example of using partials. It highlights the `Mustache.render` function.

import Mustache from 'mustache';
import { readFileSync } from 'fs';

// Basic usage
const view = {
  title: 'My Title',
  calc: () => 2 + 2,
  name: 'World'
};
const template = '<h1>{{title}}</h1><p>The answer is {{calc}}.</p><p>Hello, {{name}}!</p>';
const output = Mustache.render(template, view);
console.log('Basic Render:\n', output);

// Using a template file (e.g., 'template.mustache')
// Create a file named 'template.mustache' with content: 'User: {{username}}\nEmail: {{email}}'
try {
  const fileTemplate = readFileSync('template.mustache', 'utf8');
  const fileView = { username: 'john.doe', email: 'john@example.com' };
  const fileOutput = Mustache.render(fileTemplate, fileView);
  console.log('\nFile Render:\n', fileOutput);
} catch (error) {
  console.warn('\nCould not read template.mustache. Skipping file example.', error.message);
  console.log('To run this part, create a file named `template.mustache` in the same directory with content:');
  console.log(`User: {{username}}\nEmail: {{email}}`);
}

// Example with partials (assuming a partial named 'greet' is available)
// If you have a partials object: { greet: 'Hello {{name}}!' }
// You could then use {{> greet}} in your main template.
const partialsView = { user: 'Alice' };
const mainTemplateWithPartial = 'Main template for {{user}}! {{> greet}}';
const partials = { greet: 'Welcome, {{user}}!' };
const partialOutput = Mustache.render(mainTemplateWithPartial, partialsView, partials);
console.log('\nRender with Partials:\n', partialOutput);

view raw JSON →