Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla HTML+JS - Dynamic Interpolation?

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 Answers

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/>
like image 143
mplungjan Avatar answered Feb 22 '26 11:02

mplungjan