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'.

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

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:

var express = require('express')
var ejs = require('ejs');
var app = express();
app.set('view engine', 'ejs');
 app.get('/', function (req,res){
	res.render(hello, {message : 'Hello World!' });
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.