Home > Enterprise >  JS how to render a template from a object
JS how to render a template from a object

Time:02-19

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>

CodePudding user response:

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>

CodePudding user response:

:)

var obj = {name: "tom", address: "usa", sex: "male"};
var result;
with(obj)
    result = `<li>${name}<li><li>${address}<li><li>${sex}<li>`

or

var obj = {name: "tom", address: "usa", sex: "male"};
var template = "<li>${name}<li><li>${address}<li><li>${sex}<li>";
var result = template.replace(/\${(\w )}/g, function($0, $1) {
    return obj[$1];
});

CodePudding user response:

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>

CodePudding user response:

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>

  • Related