'JS how to render a template from a object
I have a string template such as:
template = `<li>${name}<li><li>${address}<li><li>${sex}<li>`
I have defined a object {name: "tom", address: "usa", sex: "male"} in js file.
how can I render the template by the object directly? to get result as:
<li>tom<li><li>usa<li><li>male<li>
Solution 1:[1]
Use the template literal when you access the object
I also had to fix your HTML to close the LIs
const arr = [
{ name: "tom", address: "usa", sex: "male" },
{ name: "lisa",address: "usa", sex: "female"}
];
document.getElementById('ul').innerHTML = arr
.map(({ name, address, sex}) => `<li>${name}</li><li>${address}</li><li>${sex}</li>`)
.join("")
<ul id="ul"></ul>
Solution 2:[2]
Just add obj. in the template and it should work.
var obj = {name: "tom", address: "usa", sex: "male"};
var template = `<li>${obj.name}<li><li>${obj.address}<li><li>${obj.sex}<li>`;
console.log(template);
// <li>tom<li><li>usa<li><li>male<li>
or you can destructure the object like so:
var obj = {name: "tom", address: "usa", sex: "male"};
// destructure
const { name, address, sex } = obj;
var template = `<li>${name}<li><li>${address}<li><li>${sex}<li>`;
console.log(template);
// <li>tom<li><li>usa<li><li>male<li>
Solution 3:[3]
How about a tagged template? Pass in your object to the template and have it render your HTML.
const ul = document.querySelector('ul');
const obj = { name: 'tom', address: 'usa', sex: 'male' };
function details(strings, ...rest) {
const [ name, address, sex ] = rest;
return `<li>${name}</li><li>${address}</li><li>${sex}</li>`;
}
const output = details`${obj.name}${obj.address}${obj.sex}`;
ul.innerHTML = output;
<ul></ul>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mplungjan |
| Solution 2 | Molda |
| Solution 3 | Andy |
