setup ejs template in express JS application
When we setup express JS application it comes by default with JADE template engine which is littlebit complex to use jade templates. we can configure other template engines in our express JS application. Following steps we need to follow:
we need to install ejs template library in our application using this command npm install --save ejs
after successful execution of this command ejs library will be installed in your application. next step would be replace below line in your app.js file
app.set('view engine', 'jade');
replace above statement with below one:
app.set('view engine', 'ejs');
and add below line in your app.js file where you are importing your packages/modules
var engine = require('ejs');
our view files (html files) exist in views directory in express JS application. after above changes we can create our html files with ejs extension like addressadd.ejs.
how we render ejs files in our browser. So in our route file we just need to add the path of our ejs file like this:
in the above code we are using addressadd file from users directory. this is the process we can render html file in browser in express js application. {errors: ' ', title: "Add Address" } and this is the process we can pass variables to html file from each routes.
How we setup ejs layouts in express JS application
What is ejs layouts: suppose you are working on a very large application in which most of the pages having common layouts like header and footer are same in most of the pages. if you will write header and footer in each file this is called code redundancy. How we can avoid this issue. We just simple need to configure express-ejs-layouts package in our express JS application.
First we need to use this command using CLI in our application:
npm install --save express-ejs-layouts and add below two statements in app.js file:
var expressLayouts = require('express-ejs-layouts');
app.use(expressLayouts);
in the above code we are using header and footer in the same file. In this file we are using <%- body %> tag. this tag will be replace by our module html files and we don't need to write duplicate header and footer in every html file. We will place this master layout direct in the views directory. Please refer below image:
and the question is how we can use this master layout in our module files:
in the above code we are using addressadd file from our user module. this file contains only address add form and we are using layout property in our route to use our master layout. these are the steps we can avoid html redundancy and move our common code in a master file