Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • PDF Invoice Generator
Menu

Javascript Mustache.js Example to Insert Dynamic Templates to DOM in Browser & Node.js

Posted on January 19, 2023

 

 

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.

 

 

 

 

Recent Posts

  • Build a Fixed Deposit Interest Calculator Using Amount and Time in Browser Using HTML5 & Javascript
  • How to Download Files From URL in Node.js Using Node-Downloader-Helper Library
  • Angular 10 Image Carousel and Video Gallery Lightbox Modal Slider Using ng-image-slider Library
  • React Unsplash Api Photo Search App
  • React Form Validation Using Formik and Yup
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • javascript
  • Koajs
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme