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.
Section overview
5 resourcesCovers 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
- Create a view that displays a form to create a new item. The form should include fields for the item's name and description.
-
Solution: You can create a new EJS file with a form element. The form should include two input fields and a submit button.
-
Modify the above form to include error messages if the form is submitted with empty fields.
-
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.
-
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.
- 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article