Question

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.

Was it helpful?

Solution

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top