NodeJS Express and EJS Templates
By Dan Baker, published 2010-09-25
After playing with Express, I realized it supports "View Rendering". There are three Template Engines mentioned on the Express help page. A template engine is an easy way for a web designer to create web pages that are somewhat dynamic in nature. Like a login page that displays an error message from the previous login attempt. One of the Template Engines mentioned by Express is EJS ("Embedded JavaScript templates for node - Express compliant") So, this time I'm going to discuss how to use the EJS Template Engine with Express on NodeJS. STEP 1: InstallationFrom Express: npm install express From EJS: npm install ejsThis will install Express and EJS into your NodeJS installation. STEP 2: Creating the files
app.js /views/ login.ejsCreate yourself a directory (I called mine "testejs"). We'll need an "app.js" file and a "views" folder. The views folder will need a "login.ejs" file. (The login.ejs file will contain *mosty* html. (The extension ejs tells Express to magically require the ejs system.) STEP 3: Fill in the files app.js: [javascript] var PORT = 9000; var express = require("express"); var app = express.createServer(); // special handling of the root folder app.get("/", function(req, res){ res.render('login.ejs', { layout:false }); }); // startup this server app.listen(PORT); console.log("Server on port %s", app.address().port); [/javascript] login.ejs:
<html> <body style="background-color:#cccc77"> Login<br> <table> <form method="GET" action="/"> <tr><td>Username:</td><td><input type="text" name="user"></td></tr> <tr><td>Password:</td><td><input type="password" name="pass"></td></tr> <tr><td></td><td><input type="submit" name="submit" value="Login"></td></tr> </form> </table> </body> </html> STEP 4: Run and Try it Run your app: node app.jsView your login page (which is the home page) localhost:9000 STEP 5: Dynamic Content If you have never used a template engine before (or PHP), this may be a little weird. The concept is that the .ejs file is processed on the server and the result of the process is html. That html is sent to the browser. First we will change the login.ejs file to expect a possible error message from the server. This error message will be displayed on a failed login attempt.
<h1>Login</h1> <h3 style="color:red"><%= errorMessage %></h3>The magic happens between the "<%" and "%>". That area is processed on the NodeJS Server. The "=" sign means to replace this area with the return value of the expression (in this case, the string value of a variable called "errorMessage"). Next, we will change the app.js file to send some "local data" to the ejs engine. Everything in the "locals" object is sent to the ejs system. We know the login.ejs file is expecting a variable called "errorMessage" with an error string. Note: The "locals" is in JSON format. [javascript] app.get("/", function(req, res){ res.render('login.ejs', { layout:false, locals: { errorMessage: "Error: password wrong." } }); }); [/javascript] View your new dynamic login page. The awesomeness of using a template system like EJS is that the html can live on the disk in a file. That file can be generated by a web designer, using web designer tools. Obviously, the web designer has to know what "locals" data will be sent to the page (like "errorMessage"). STEP 6: Configuration If you rarely use layouts you can add the following to your app.js, and remove the "layout:false" from the res.render call: [javascript] app.set('view options', { layout: false }); [/javascript] If you are only going to use a single Template Engine then you can add the following to your app.js, and never have to specify the extension on your res.render call: [javascript] app.set('view engine', 'ejs'); [/javascript] This leaves our "get" to be the following: [javascript] app.get("/", function(req, res){ res.render('login', { locals: { errorMessage: "Error: password wrong." } }); }); [/javascript] Of course, the error message would be created in code, after checking the login credentials. But, you get the idea. Other things to look into: Layouts View Partials