Thursday, July 05, 2012

Fiddle with EJS filters

Lets play with EJS filters a bit. Lets pay greetings to the first user in the array of names with a message as "Welcome <firstname> <lastname>"

Lets take the names in an array of objects as below:

var names = [{first: 'John', last: 'Scott'},
             {first: 'Rob', last: 'Miller'}];

Now lets create a filter to create the message, in this filter the first selected object will be passes, which comes from the previous filter "first"

ejs.filters.greeting = function(user){
  return 'Welcome ' + user.first + ' ' + user.last + '';
};

The call to the filter is made in the index.ejs file as below, here insted of first you can can also use last filter

<%=: users | first | greeting %>

Lets see the whole program.

server.js
var express = require('express');
var io = require('socket.io');
var http = require('http');
var ejs = require('ejs');
 
var app = express();
var server = http.createServer(app);
 
var names = [{first: 'John', last: 'Scott'},
             {first: 'Rob', last: 'Miller'}];
 
app.configure(function(){
  app.use(express.bodyParser());
  app.use(app.router);
  app.use(express.static(__dirname + '/'));
  app.set('view engine', 'ejs');
  app.set('view options', {
    layout: false
  });
});
 
ejs.filters.greeting = function(user){
  return 'Welcome ' + user.first + ' ' + user.last + '';
};
 
app.get('/', function(req, res) {
  res.render('index', {
    title : 'Welcome to Express EJS',
    users: names
  });
});
 
server.listen(8080);

index.ejs
<html>
 
<head>
<title><%= title %></title>
</head>
 
<body>
<p><%=: users | last | greeting %></p>
</body>
 
</html>