简体   繁体   中英

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 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM