Welcome folks today in this blog post we will be using the Mustache.js
library to insert dynamic templates
to DOM in browser using node.js and javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<html> <body> <form id="form"> <input type="text" name="" id="name" placeholder="Enter name" required /> <input type="submit" value="Change Name" /> </form> <div id="target">Loading...</div> <script id="template" type="x-tmpl-mustache"> Hello {{ name }}! </script> <script src="https://unpkg.com/mustache@latest"></script> <script> let form = document.getElementById("form"); form.addEventListener("submit", changeName); function changeName(e) { e.preventDefault(); var template = document.getElementById("template").innerHTML; var rendered = Mustache.render(template, { name: document.getElementById("name").value, }); document.getElementById("target").innerHTML = rendered; } </script> </body> </html> |
As you can see we are including the mustache.js
library cdn and then we are having the html5
form to allow the user to submit the dynamic
username and then we are inserting this name into the html5
template.