By using view engine, we can inject dynamic content in the html.
In this tutorial we are going to use ejs view engine.
1. Installing ejs
npm install ejs
will install the ejs package.
2. Registering ejs
ejs have to be registered after we create the express app.
const app = express();
app.set('view engine', 'ejs');
By default the templates will be searched in /views
folder. We can change the setting explicitly.
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'myviews');
Then templates will be searched in '/myviews' folder.
3. Rendering HTML Pages
Instead of res.sendFile()
we are going to use app.render()
app.get('/', (req, res) => {
res.render('index');
// AND NOT res.sendFile('./views/index.html', ...);
})
res.render('index')
: inside render we are going to place the filename without the extension.
4. Passing Data into views
app.get('/about', (req, res) => {
res.render('about', { title: 'About' });
})
Now, title
will be accessible from templates in the following way:
<%= title %>
if-else in ejs
<% if (blogs.length > 0) { %>
<h3><%= blogs.length %> posts to display %>
<% } else { %>
<h3>No Blog Posts to display...</h3>
<% } %>
for loop in ejs
<% blogs.forEach(blog => { %>
<%= blog.title %>
<% }) %>
To print data <%= data %>
is used and to write logic <% logic %>
is used.
A shortcut
In app.js
app.get('/', (req, res) => {
res.render('index', { numbers: numbers });
})
Instead of this,
app.get('/', (req, res) => {
res.render('index', { numbers });
})
Instead of {numbers: numbers}
, we can use { numbers }
.
5. Partial
Assume the following ejs file
<html>
<head>
A long header
</head>
<body>
<nav>
A complicated navbar
</nav>
<div>
...
content of page 1
...
</div>
<footer>
common footer
</footer>
</body>
</html>
Now, suppose we have 50 such pages.
We can cut the nav, head, and footer as they are common in every page and place them nav.ejs, head.ejs and footer.ejs file respectively
<!--nav.ejs-->
<nav>
A complicated navbar
</nav>
<!--head.ejs-->
<head>
A long header
</head>
<!--footer.ejs-->
<footer>
common footer
</footer>
Then the structure of the 50 pages will be reduced to:
<html>
<%- include('./partials/head.ejs') %>
<body>
<%- include('./partials/nav.ejs') %>
<div>
...
content goes here
...
</div>
<%- include('./partials/footer.ejs') %>
</body>
</html>
Top comments (0)