Sunday, 17 March 2019

Express: res.render(view [, locals] [, callback])


res.render(view [, locals] [, callback])
Render the view and send the rendered html content to the client.

In this post, I am going to explain how to integrate express with EJS (Embedded JavaScript templates, templates are used to separate the presentation from the business logic). EJS is one of the popular view engine.

First step is to install ejs module by executing below statement.
npm install ejs

We should inform the express application that we are using EJS view engine. You can specify that by adding below statements in express application.

app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs");

First statement checks for the views in /views directory.

For example, below snippet maps the home page to hello.js file. As you see first argument of response.render() method is "hello", that means, view engine look for the file hello.ejs and render it.

app.get('/', (request, response) => response.render("hello", {
                  message: "Hey everyone! This is my webpage."
         })
);

You can access the 'message' property defined in render method from hello.ejs file like below.
<%= message %>

Project structure looks like below.


hello.ejs
<html>

 <head>
  <title>Express and EJS integration</title>
  <meta charset="utf-8">
 </head>
 
 <body>
  <h1>
   <%= message %>
  </h1>
 </body>
</html>



HelloWorld.js
//Load express module
const express = require('express');
const path = require('path');

//Put new Express application inside app variable
const app = express();

//Set views property and views engine
app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs");

const port = 8080;

//When user hits the home page, then the message prints in browser.
app.get('/', (request, response) => response.render("hello", {
  message: "Welcome to express and ejs 'Hello World' application"
 })
);

// Start the express application on port 8080 and print server start message to console.
app.listen(port, () => console.log(`Application started listening on port ${port}!`));

Run HelloWorld.js by executing below command.
node HelloWorld.js


Open browser and hit the url 'http://localhost:8080/', you can see below message in the browser.






Previous                                                 Next                                                 Home

No comments:

Post a Comment