Tech notes for mustachejs

undefined

Posts

  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: [
      "java",
      "script",
      "javascript"
    ]
  }
  var html = `
    <div>
      hello {{name}}
    </div>
    <div>
      hello {{{name}}}
    </div>
    {{#hobbies}}
      <div>{{.}}</div>
    {{/hobbies}}`

  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.

animals.map((e, i) => { return {e: e, i: i} })

Integrate that with mustache.js and you get

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

Page 1 of 1
Click me