Not able to display output in form of html table when rendered to the .hbs file. When I write res.send() it displays in the HTML format that I wanted to show but when I do res.render it does not display it in the HTML format instead it also shows my table and row tags in the output
app.get('/data/search/title', (req, res, next) => {
res.render('form_process_title', { name: 'Form Title' });
});
When I hit the above url data/search/title it takes me to the form_process_title.hbs file which is below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Welcome to {{ name }} page</h1>
<form method="POST" action="/form_route_title">
<input type="text" name="title" placeholder="title">
<input type="submit">
</form>
<p>{{ans}}</p>
</body>
</html>
After submitting the form I will get redirected to the below route
app.post('/form_route_title', function (req, res, next) {
var ans = "<table border = 3>";
ans += "<tr>";
ans += "<td>" + "Title" + "</td>";
ans += "<td>" + "ISBN" + "</td>";
ans += "<td>" + "Description" + "</td>" + "</tr>";
var count = 0;
try {
// console.log(req.body.title);
let data = JSON.parse(fs.readFileSync('myData.json'));
for (var i = 0; i < data.length; i++) {
if (data[i].title.includes(req.body.title)) {
ans += "<tr>";
count++;
ans += "<td>" + data[i].title + "</td>";
ans += "<td>" + data[i].isbn + "</td>";
ans += "<td>" + data[i].shortDescription + "</td>";
ans += "</tr>";
}
}
ans += "</table>";
console.log("Count = " + count);
res.render('form_process_title', { name: 'Form Title', ans: ans });
//res.send(ans);
}
catch {
res.render('form_process_title', { name: 'Form Title', ans: "Sorry the data does not exist" });
//res.send("Sorry the data at this index does not exist")
}
});
When I do res.send(ans) it works perfectly but I want it to work in the below step - res.render('form_process_title', { name: 'Form Title', ans: ans });
From the above images you can see that I am not getting the desired output.
I am expecting the output to be displayed in the HTML table format not just the tags.
{{ans}}
` with `{{{ans}}}` - the triple mustaches tell Handlebars not to HTML-escape. But I would advise you not to put all of that table HTML into a variable. HTML belongs in your Handlebars templates. – 76484 Nov 01 '22 at 16:36