How to implement res.render() function?
The res.render() function is typically used in web development frameworks like Express.js in Node.js applications to render HTML templates and pass data to them. To implement a simplified version of res.render() in HTML and JavaScript, you can create a function that takes a template and data as input and generates HTML output.
Here's a basic implementation of res.render() in HTML and JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Render Function</title>
</head>
<body>
<!-- Define a template in HTML -->
<script id="template" type="text/html">
<h1>{{ title }}</h1>
<p>{{ content }}</p>
</script>
<script>
function render(templateId, data) {
// Get the template content
var template = document.getElementById(templateId).innerHTML;
// Replace placeholders in the template with actual data
for (var key in data) {
var regex = new RegExp('{{\\s*' + key + '\\s*}}', 'g');
template = template.replace(regex, data[key]);
}
// Render the template
document.body.innerHTML = template;
}
// Example usage
var data = {
title: "Welcome to My Website",
content: "This is a simple example of rendering HTML using a custom render function."
};
// Call the render function with the template ID and data
render("template", data);
</script>
</body>
</html>
In this implementation:
- We define an HTML template inside a <script> tag with the type text/html. This template contains placeholders enclosed within double curly braces ({{ }}) that will be replaced with actual data.
- The render function takes two parameters: the ID of the template element and the data object containing values to be rendered in the template.
- Inside the render function, we retrieve the template content by its ID, then loop through the data object and replace each placeholder in the template with the corresponding value.
- Finally, we render the modified template by setting the innerHTML of the document.body to the updated template content.
Index.js
Inside the file, we first require the Express framework to be able to use it. We create an app that uses the view engine setup. Inside app.get we call the function res.render(), with the parameter as the name of home.ejs file.
var express = require('express');
var app = express();
var PORT = 3000;
// View engine setup
app.set('view engine', 'ejs');
// Without middleware
app.get('/user', function(req, res){
// Rendering home.ejs page
res.render('home');
})
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Home.ejs
<html>
<head>
<title>res.render() Demo</title>
</head>
<body>
<h2>Welcome to Coding Ninjas</h2>
</body>
</html>
Output
Steps to run the program:
Now, To run the above program we use the following command
npm index.js
Console Output:
Server listening on PORT 3000
This message indicates that the Express server has started and is listening on port 3000.
Browser Output:
In the browser, the HTML content is rendered by the home.ejs template. The browser will display this content as a webpage with the title "res.render() Demo" and the heading "Welcome to Coding Ninjas".
Different forms of res.render() function
The res.render() function can take different forms because of the various parameters in it, all the possible forms are shown below.
// send the rendered view to the client
res.render('index')
// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function (err, html) {
res.send(html)
})
// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function (err, html) {
// ...
})
Now, we have a clear understanding of the res.render() function in Express.
Also see - Difference between argument and parameter
Frequently Asked Questions
What is res.render() function?
The function used to render an HTML view and to send the rendered HTML data to the client is known as the res.render() function.
What is the use of res?
res is an object in Express.js used to send HTTP responses, including rendering HTML templates or sending JSON data.
What is the difference between res render and res json?
res.render renders HTML templates, while res.json sends JSON data. The former is for webpages, the latter for APIs.
What are the parameters in the res.render() function?
res.render() has two parameters, namely locals and a callback function (optional).
Conclusion
We learned about the concept of render function in Express. We learned about the need for res.render() in Express. We also briefly looked at its implementation.
Recommended Reading
Check out some of the Guided Paths on topics such as Data Structure and Algorithms and some Courses brought to you by leading industry experts on topics such as Java, Full Stack Web Development, etc. along with some Interview Bundles and Test Series to give you the edge only on Coding Ninjas Studio.
Happy Learning!