Rendering Forms with EJS
Rendering forms with EJS (Embedded JavaScript) involves creating HTML forms that users can interact with, such as submitting data to a server. EJS allows you to dynamically generate form elements and handle form submissions using template variables and server-side data.
Rendering Forms with EJS
1. Basic Form Rendering
To render a form in EJS, you use standard HTML form elements within your EJS template. You can dynamically populate form fields with data from the server or include template variables.
Example:
Form Page (views/form.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Page</title>
</head>
<body>
<h1>Submit Your Information</h1>
<form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= name || '' %>" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="<%= email || '' %>" required>
<label for="age">Age:</label>
<input type="number" id="age" name="age" value="<%= age || '' %>">
<button type="submit">Submit</button>
</form>
</body>
</html>
In this example:
<%= name || '' %>
: If aname
variable is passed from the server, it will be used as the default value in the input field. If not, the field will be empty.- The form uses
POST
method and submits data to/submit
URL.
2. Populating Form Fields with Data
You can pre-fill form fields with data fetched from a database or passed from the server. This is useful for creating or editing records.
Server-Side Code (Express):
app.get('/edit/:id', async (req, res) => {
const id = req.params.id;
// Fetch user data from database
const user = await User.findById(id);
res.render('form', {
name: user.name,
email: user.email,
age: user.age
});
});
Edit Form (views/form.ejs
):
<form action="/update/<%= id %>" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= name || '' %>" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="<%= email || '' %>" required>
<label for="age">Age:</label>
<input type="number" id="age" name="age" value="<%= age || '' %>">
<button type="submit">Update</button>
</form>
In this example:
- The
value
attributes of the input fields are populated with the user data fetched from the database.
3. Handling Form Submissions
When a form is submitted, it sends data to a specified URL using the POST
method. You need to handle this data on the server side to process it, validate it, and save it to a database.
Server-Side Code (Express):
app.post('/submit', (req, res) => {
const { name, email, age } = req.body;
// Process the form data, e.g., save to database
console.log(`Name: ${name}, Email: ${email}, Age: ${age}`);
res.redirect('/');
});
Example of Handling Form Data:
- Use
req.body
to access form data sent in thePOST
request. - Validate and process the data as needed before saving it to a database or performing other actions.
4. Error Handling and Validation
To handle validation errors and redisplay the form with error messages, you can pass error messages from the server to the template.
Server-Side Code (Express):
app.post('/submit', (req, res) => {
const { name, email, age } = req.body;
let errors = [];
if (!name) errors.push('Name is required.');
if (!email) errors.push('Email is required.');
if (errors.length > 0) {
res.render('form', { name, email, age, errors });
} else {
// Process the data
res.redirect('/');
}
});
Form Page with Error Display (views/form.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Page</title>
</head>
<body>
<h1>Submit Your Information</h1>
<% if (errors && errors.length > 0) { %>
<ul>
<% errors.forEach(error => { %>
<li><%= error %></li>
<% }); %>
</ul>
<% } %>
<form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= name || '' %>" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="<%= email || '' %>" required>
<label for="age">Age:</label>
<input type="number" id="age" name="age" value="<%= age || '' %>">
<button type="submit">Submit</button>
</form>
</body>
</html>
In this example:
- Error messages are displayed above the form if validation fails.
- The form fields retain their values after submission to allow users to correct their input.
Summary
- Basic Form Rendering: Use HTML form elements and EJS template variables to render forms.
- Pre-Filling Fields: Populate form fields with server-side data for creating or editing records.
- Handling Submissions: Process form data on the server and handle form submissions.
- Error Handling: Display validation errors and retain form data for user correction.
By using EJS to render forms, you can dynamically generate form content based on server-side data and manage form submissions effectively.