I want to use Mustache to generate a dedicated HTML page for each object of an array, whenever we click the "contact him" link. However, it looks like the link is generated only for one user.
My question: How can I have a dedicated page for each object of the array, instead of having the same link for every objects of the array?
Here is the code to reproduce the case:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="test-id">
<!-- Generated Content -->
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
<script src="mustache.js"></script>
</body>
</html>
template_page.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="template-div">
<!-- part filled by Mustache -->
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
<script src="mustache.js"></script>
</body>
</html>
main.js
document.addEventListener('DOMContentLoaded', function() {
var ALL_DATA = [
{
'lastname': 'lastname_1',
'firstname': 'firstname_1'
},
{
'lastname': 'lastname_2',
'firstname': 'firstname_2'
},
{
'lastname': 'lastname_3',
'firstname': 'firstname_3'
}
];
function displayData(obj_name) {
var theDiv = document.getElementById("test-id");
obj_name.forEach(doc => {
var lastname = doc['lastname'];
var firstname = doc['firstname'];
console.log("found");
console.log(doc);
newdiv = document.createElement("div")
var text = document.createTextNode(lastname + ' ' + firstname);
var anchor_value = document.createElement("a")
anchor_value.setAttribute("href", "template_page.html");
anchor_value.setAttribute("class", "link-a");
anchor_value.onclick = createPage(doc);
anchor_value.appendChild(document.createTextNode("Contact him"));
newdiv.appendChild(text);
newdiv.appendChild(anchor_value);
theDiv.appendChild(newdiv);
});
};
displayData(ALL_DATA);
function createPage(data) {
console.log("found2");
console.log(data);
var template =
`
<h1> Welcome, {{firstname}} </h1>
<h2> Your last name: {{lastname}} </h2>
`
var html = Mustache.render(template, data);
$("#template-div").html(html);
};
});
(mustache.js also needed)