Tech notes for mustachejs



  1. ExpressJS & MustacheJS: Quick setup
  2. MustacheJS: Get the index in an array

ExpressJS & MustacheJS: Quick setup

npm install mustache

Then import the render function (I'm going to rename render to mustache): const { render: mustache } = require('mustache')

The first argument to mustache is the text. The second is the object with the template variables.

{{variable_name}} html escapes the content. {{{variable_name}}} doesn't.

Start a list with {{#variable_name}} and end it with {{/variable_name}}. Each item is {{.}}. If the item is an object, get a field with {{field_name}}.

const express = require('express')
const { render: mustache } = require('mustache')
const app = express()
app.listen(3000, _ => console.log("started on 3000"))

app.get("/", (req, res) => {
  var context = {
    name: "<b>david divad</b>",
    hobbies: [
  var html = `
      hello {{name}}
      hello {{{name}}}

  res.send(mustache(html, context))
expressjs mustachejs nodejs

MustacheJS: Get the index in an array

Let's fix Mustache.js looping through arrays but not finding the index.

Let's say we have the array animals = ["dogs", "cats", "wild boars"].

We can map this into an array of value-index objects., i) => { return {e: e, i: i} })

Integrate that with mustache.js and you get

return Mustache.render(`
      <li>{{i}} {{e}}</li>
  { animals_indexed: _ =>,i)=> { return {e:e,i:i} } )
javascript mustachejs

Page 1 of 1
Click me