Skip to content Skip to sidebar Skip to footer

How To Use Es6 Template Literals With External Html File

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 th

Solution 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 = /\{(.*?)\}/glet finalMarkup = markupFromExternalFile
const changes = finalMarkup.matchAll(regex)

while(true) {
  const change = changes.next()
  if(change.done) breakconst [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.

Post a Comment for "How To Use Es6 Template Literals With External Html File"