Vanilla HTML+JS - Dynamic Interpolation?

ⅰ亾dé卋堺 提交于 2021-02-16 18:27:27

问题


I know that in frameworks like Handlebars and ect. it is possible to write HTML similar to the following:

<span id="logged-on-username">{{username}}</span>

In this contrived example, a JS file loaded when on this page would return the value of a variable called username and interpolate it into the view template.

Is anything similar possible in vanilla HTML + JS?

Thanks in advance for anyone's time who happens to answer.


回答1:


You mean something like this

const content = {
  "username": "Fredy Kruger",
  "status": "Scary",
}
window.addEventListener("load", function() {
  [...document.querySelectorAll("span.dynamic")].forEach(span => {
    const match = span.textContent.match(/{{(.*?)}}/)
    if (match.length === 2) span.innerText = content[match[1]]
  })
})
Name: <span class="dynamic" id="logged-on-username">{{username}}</span><br/> 
Status: <span class="dynamic">{{status}}</span><br/>


来源:https://stackoverflow.com/questions/62382939/vanilla-htmljs-dynamic-interpolation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!