How to use HTML in Express framework with nunjucks- no jade

Merlin picture Merlin · Nov 11, 2013 · Viewed 12.4k times · Source

I have been using sendFile method to render Html in Express project. I would like to use partials with my project. And, not switch to jade.

Is there a way to use traditional HTML with partials in Express 3.x. I have tried ejs, but dont understand it completely.

Answer

robertklep picture robertklep · Nov 11, 2013

A more 'HTML-like' templating engine would be nunjucks (whose syntax is similar to Jinja2, which you have experience with).

Here's a simple setup. This assumes both Express and Nunjucks are installed, if not:

npm install express
npm install nunjucks

app.js

var nunjucks  = require('nunjucks');
var express   = require('express');
var app       = express();

app.listen(3012);

nunjucks.configure('views', {
  autoescape: true,
  express   : app
});

app.get('/', function(req, res) {
  res.render('index.html', {
    title : 'My First Nunjucks Page',
    items : [
      { name : 'item #1' },
      { name : 'item #2' },
      { name : 'item #3' },
      { name : 'item #4' },
    ]
  });
});

views/index.html

<!doctype html>
<html>
  <head>
    <title>welcome to {{ title }}</title>
  </head>
  <body>
    <ul>
      {% for item in items %}
        {% include "item.html" %}
      {% endfor %}
    </ul>
  </body>
</html>

views/item.html

<li>{{ item.name }}</li>