LearnFast.Ninja

Using mustache with node.js and express

How to use mustache for client side template engine and node.js + express as server side and MongoDB as database.

Step 1:
Using npm install the node module mustache-express:

Step 2:
Make sure you have express in your node project.
Write this server:

// require ================================================================

var         express = require("express"),                   // web development framework
            mustacheExpress = require('mustache-express');  // Logic-less {{mustache}} templates

// express ===============================================================

var app = express();

// configure =============================================================
app.engine('html', mustacheExpress());          // register file extension mustache

app.set('view engine', 'html');                 // register file extension for partials
app.set('views', __dirname + '/html');

app.use(express.static(__dirname + '/public')); // set static folder

// routes =================================================================
app.get(
'/', function(req, res) {
    res.render(
'master', {
            head: {
                  title:
'page title'

            },
            content: {
                  title:
'post title',

                  description: 'description'
            }
        });
    });
app.listen(process.env.PORT || 3000);


Step 3:
Create html folder with html files.


Step 4:
Server side example + MongoDB

// Routes =================================================================
exports.routes = function(app) {
      app.get(
'/',  exports.findAll);

}

 

//var db = ...

 

exports.findAll = function(req, res) {

      db.collection(collectionName, function(err, collection) {

      var filterRowStatus = { row_status: '0' };
     
var sort = { date_created: -1 };
      collection.find(filterRowStatus).sort(sort).toArray(
function(err, items) {

            res.render('master', {

                head: {

                  title: 'Your title here'
                },
                homepage: {

                  items: items

                }

            });
        });
    });

};


Step 5:
master.html

<!DOCTYPE html>

<html>

<head>

</head>
<
body>
      {{>homepage}}

</body>


homepage.html

<h1>{{homepage.title}}</h1>

<ul>

{{#homepage.items}}

      <li><a href="posts/{{_id}}">{{title}}</a></li>
{{/homepage.items}}
</ul>


Result:


Tags

mustache

node.js express mongodb