Home » Node.js

How to use EJS with Express in Node.js?

In this article, we are going to learn how to route through parameters in Node.js?
Submitted by Manu Jemini, on November 27, 2017

It's about how to use EJS with Express. If you don’t want to use a front-end framework like Angular or React, you will definitely need a template engine with EXPRESS and EJS is one of the easiest ways to start with.

This tutorial will lead you through everything which you need to set your environment. Keep in mind that you have multiple ways to approach the same result. Feel free to explore other approaches as well, but this is one of the easiest one to start with.

  • First, make an Express project any way you want.
  • Second thing is to download EJS for node modules. For this have an internet connection and open your command prompt in the project directory. Then Enter this simple command: npm install ejs.
  • When you are done with your downloading and all. Open up your text editor and start coding in the file of your choice.
  • Now make a file with an extension of '.ejs' in your project directory.

When you are done with this, make your file look like this, keep the file name 'hello.ejs'.

<html>
	<h1><%= message %></h1>
</html>

This is very simple code. You need to learn to EJS itself and this tutorial is about how to use both of them together?

Now make your express server file like this:

//step-1
var express = require('express')
//step-2
var ejs = require('ejs');
//step-3
var app = express();
//step-4
app.set('view engine', 'ejs');
//step-5
 app.get('/', function (req,res){
	res.render(hello, {message : 'Hello World!' });
})
//step-6
app.listen(3000,function(){
console.log("server is running");
})

Discussing steps that we have followed in our server file:

  • Require Express module.
  • Require ejs module.
  • Using express.
  • Set ejs as view engine using app.set() method.
  • Set listener with .get method and render the message.
  • Listen to port 3000.


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.