Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
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

  • Android Java Project to Merge Multiple PDF Documents From Gallery Using iTextPDF Library
  • Android Java Project to Detect System Hardware & System CPU Info & Display inside TextView Widget
  • Android Java Project to Integrate Google OAuth2 Login & Logout System & Save User Info in SharedPreferences
  • Android Java Project to Export Raw Text to PDF Document Using iTextPDF Library
  • Android Java Project to Export Images From Gallery to PDF Document Using iTextPDF Library
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme