Search code examples
javascripthtmlinterpolationtemplating-engine

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.


Solution

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