Express by Examples

EJS Template Engine

EJS stands for Embed JavaScript. It is template engine mostly used for nodeJS - Express.

Here will be explained basics. For more info visit http://www.embeddedjs.com/ .

 

Installation

$npm install --save ejs

In express ./app.js file put:

var ejs = require('ejs');

app.set('view engine', 'ejs');

 

The complete app.js file should look like:

/*jslint unparam: true*/

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ejs = require('ejs');

//session
var session = require('express-session');
var FileStore = require('session-file-store')(session);

var routes = require('./routes/index');
var admin_index = require('./routes/admin/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/images/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public'))); //__dirname = "/homenode/find-ads"

//session
var sess_options = {
  path: "./tmp/sessions/",
  useAsync: true,
  reapInterval: 5000,
  maxAge: 10000
};
app.use(session({
  store: new FileStore(sess_options),
  secret: '2015tajnikljuc',
  resave: true,
  saveUninitialized: true
}));



app.use('/', routes);
app.use('/admin', admin_index);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

 

 

Caution:

1. All files in /views/ folder must have .ejs extension, for example:  index.ejs

2. Don't forget to create template for catching errors:

./views/error.ejs

<h1><%= message %></h1>
<h2><%= error.status %></h2>
<pre><%= error.stack %></pre>

 

 

Output Variable or object property

1. escaping special chars <%=  %>

<%= var %>

<%= object.property %>

 

Here HTML special chars are escaped. Fore example " is escaped into &#34;

 

2. non escaping special chars <%-  %>

 

 

Iterate object

 

 

Iterate array

 

If statement

<%= var ? var : '' %>   - echo 'var' if and only if 'var' exists