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
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
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');
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>
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' });
});
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'] });
});
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
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.