Express.js / Express.js with Template Engines

Using EJS with Express.js

In this tutorial, you'll learn how to use EJS (Embedded JavaScript) as your template engine with Express.js. We'll cover installation, setup, and basic usage.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers using template engines like EJS, Pug, and Handlebars to render dynamic views.

1. Introduction

In this tutorial, we'll learn how to use EJS (Embedded JavaScript) with Express.js. EJS allows us to create dynamic HTML content with plain JavaScript. Express.js, on the other hand, is a web application framework for Node.js.

By the end of this tutorial, you will learn how to set up EJS as a template engine for Express.js, how to create and render EJS views, and how to pass data to views.

Prerequisites:
- Basic knowledge of JavaScript and HTML
- Node.js and NPM installed on your machine

2. Step-by-Step Guide

Installation

First, let's create a new Express.js application. In your terminal, run:

npx express-generator myapp

This will generate a new Express.js application in a folder named "myapp". Now, navigate into the new folder and install EJS:

cd myapp
npm install ejs

Setting up EJS

To use EJS with Express.js, we need to set EJS as the view engine for our application. In the app.js file, add the following lines of code:

app.set('view engine', 'ejs');

Creating EJS Views

In your "views" folder, you can now create EJS files. These files end with the .ejs extension and can include plain HTML and JavaScript code within <% %> tags.

For example, create a new file index.ejs in the "views" folder and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>My App</title>
</head>
<body>
    <h1>Welcome to <%= title %>!</h1>
</body>
</html>

Rendering EJS Views

To render an EJS view, use res.render() in your route handlers. This method takes the name of the view and the data that should be passed to the view. For example, in your routes/index.js file, you can add:

router.get('/', function(req, res, next) {
  res.render('index', { title: 'My App' });
});

3. Code Examples

Let's create a more complex view that displays a list of items. Create a new file list.ejs in the "views" folder and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>My App</title>
</head>
<body>
    <h1>Items:</h1>
    <ul>
        <% items.forEach(function(item) { %>
            <li><%= item %></li>
        <% }); %>
    </ul>
</body>
</html>

In your routes/index.js file, you can now render this view with some data:

router.get('/list', function(req, res, next) {
  res.render('list', { items: ['Item 1', 'Item 2', 'Item 3'] });
});

4. Summary

In this tutorial, we've learned how to set up EJS with Express.js, create and render EJS views, and pass data to these views. Next, you could learn more about EJS syntax and features, such as conditionals and includes.

Additional resources:
- EJS Documentation
- Express.js Documentation

5. Practice Exercises

  1. Create a view that displays a form to create a new item. The form should include fields for the item's name and description.
  2. Solution: You can create a new EJS file with a form element. The form should include two input fields and a submit button.

  3. Modify the above form to include error messages if the form is submitted with empty fields.

  4. Solution: You can use EJS conditionals to display error messages. In your route handler, check if the form data is valid and pass an error message to the view if it's not.

  5. Create a view that displays a list of items and a form to add a new item. When a new item is added, it should appear in the list without reloading the page.

  6. Solution: This requires some knowledge of AJAX. You can use the Fetch API or jQuery to send a POST request when the form is submitted, then update the list on the client side.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Unit Converter

Convert between different measurement units.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help