2

i build a web app that is combined with lots of screens that i want to load parts of them each time. so i use data object and html markup. but since i load many templates i want the html data to be parsed on small html files that will be read when the webapp need them.

const customer = {
    name: 'john doe',
    title: 'Web Developer',
    city: 'NY'
}

const markup = `
 <div class="customer">
    <h2>
        ${customer.name}
    </h2>
    <p class="location">${customer.location}</p>
    <p class="title">${customer.title}</p>
 </div>
`;

what i actually want is that the markup html will be taken from external file

so i tried to get the template string by calling ajax and saving the html as a variable, but it seems not to parse the template literals

any help would be greatly appriciated

sd1sd1
  • 1,028
  • 3
  • 15
  • 28

1 Answers1

1

Well, there's no in-built data binding in HTML, the functionality offered by frameworks like Angular. But still, if you want to stay vanilla, you could go with something like this:

const customer = {
    name: 'john doe',
    title: 'Web Developer',
    city: 'NY'
}

const markupFromExternalFile = `
 <div class="customer">
    <h2>
        {customer.name}
    </h2>
    <p class="location">{customer.city}</p>
    <p class="title">{customer.title}</p>
 </div>
`

const regex = /\{(.*?)\}/g

let finalMarkup = markupFromExternalFile
const changes = finalMarkup.matchAll(regex)

while(true) {
  const change = changes.next()
  if(change.done) break
  const [replacement, prop] = change.value
  finalMarkup = finalMarkup.replace(replacement, customer[prop.split('.').pop()])
}

console.log(finalMarkup)

Here, make sure that your property names in the HTML markup match with the property name of your object from which you're picking it up.

mehulmpt
  • 15,861
  • 12
  • 48
  • 88
  • thanks. one more question, can it be used with map function? to loop through list of users? – sd1sd1 Jul 18 '19 at 19:39
  • Definitely. Just wrap everything after that regex initialization into a map function and it should work. @sd1sd1 – mehulmpt Jul 18 '19 at 19:43