Revamping a design using Mustache js

I've successfully implemented mustache js to render a template using data from an API, but now I face a challenge in updating the same template at a later time. Within my template, there is a list structured like this:

template.html

<div id="template">
  {{#list}}
    <span>{{firstName}} {{lastName}} - {{phone}}</span>
  {{/list}}
</div>

index.js

$(document).ready(function(){

  $.ajax(
    //Placeholder for actual AJAX code
  ).done(function(response){
    loadTemplate(response);
  });

});

function loadTemplate(data){
  var template = $("#template").html();
  Mustache.parse(template);
  var render = Mustache.to_html(template, data);
  $("#template").empty().html(render);
};

Users have the ability to add more elements to this list, and I need the mustache template to reflect these additions. I attempted to trigger an AJAX call that responds with the updated list values, followed by calling the loadTemplate function again. However, the list does not update as expected.

Answer №1

When you initially render the template, the original mustache template disappears. ONLY the text that is rendered remains in the same location. So if you try to re-render the template a second time, there is no actual template to render, only text that is no longer a template and will simply be outputted again.

The trick is to keep your original template stored in a different location (for example, inside an element with id=#originalTemplate).

Here's what you need to do:

function loadTemplate(data){
  var template = $("#originalTemplate").html(); // Remember, we're using the original template that doesn't get replaced
  Mustache.parse(template);
  var render = Mustache.to_html(template, data);
  $("#template").empty().html(render);
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Include the JS file after finishing the control processing

I've been grappling with an issue for several days now. The view I have is populated by my controller through an API call, which works perfectly fine in rendering the HTML. $http.get(url). success(function(data, status, headers, config) { ...

Simple Method to Retrieve one document from Firebase v9 in a React Application

Is it possible to retrieve a document from Firebasev9 using a slug instead of an id with the useDocument Hook? useDocument Hook import { useEffect, useState } from "react" // firebase import import { doc, onSnapshot } from "firebase/firesto ...

Is there a way to construct a Javascript function, without relying on JQuery, for fetching JSON objects from varying

I have been searching for a non-JQuery AJAX function that can fetch data from a URL and return it as a JSON object. For example, let's say I want to display information about Users from one JSON located at URL1 and also include information about Post ...

Using jQuery to create a blinking effect on a specific letter in a string

I'm looking to create a text adventure using Canvas, and I want the parser to blink continuously, similar to the one in a Dos Console. The parser is stored as a global variable. How can I use jQuery to permanently change the character of this global v ...

The AngularJS directive seems to be having trouble receiving the data being passed through its scope

Check out this HTML code snippet I created: <div ng-controller="ctrl"> <custom-tag title = "name" body = "content"> </custom-tag> </div> Take a look at the controller and directive implementation below: var mod = angular.mod ...

Unable to display divs in a stacked format using Bootstrap 5

I need help aligning div's vertically on the page. Currently, all my elements are displaying next to each other instead of stacking one below the other. body { height: 100vh; } <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi ...

Adjust scale sizes of various layers using a script

I have created a script in Photoshop to adjust the scale size of multiple layers, but I am encountering some inaccuracies. The script is designed to resize both the width and height of the selected layers to 76.39%. However, when testing the script, I foun ...

Passing a leading zero function as an argument in JavaScript

Is there a method for JavaScript to interpret leading zeros as arguments (with the primitive value as number)? I currently have this code: let noLeadingZero = (number) => { return number } console.log('noLeadingZero(00):', noLeadin ...

Issues with ng-repeat causing the Angular Editable table to malfunction

<table class="table table-bordered"> <tbody> <tr ng-repeat="playerOrTeam in template.editableTable track by $index"> <td style="text-align: center;" ng-repeat="playerOrTeamCat in playerOrTeam track by $index"> ...

What is the best way to test the Express router catch branch in this specific scenario with Jest?

My current task involves working with a file containing two routes. The first route is located in routes/index.js const express = require('express') const router = express.Router() router.get('', (req, res, next) => { try { r ...

Sending Location Data From JavaScript to PHP via Cookies

I encountered an issue while attempting to send Geolocation coordinates from JavaScript to PHP using Cookies. The error message I am receiving is: Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/samepage.php on line 24 The file name ...

Node timers exhibiting unexpected behavior contrary to documented specifications

Feeling a bit lost with this one. I'm running Ubuntu and using nvm for node. I made sure to uninstall the version of node installed via apt just to be safe. node --version > v10.10.0 npm --version > 6.4.1 So, I go ahead and create-react-app a ...

Is all of the app fetched by Next.js when the initial request is sent?

After doing some research online, I learned that Next.js utilizes client-side routing. This means that when you make the first request, all pages are fetched from the server. Subsequent requests will render those pages in the browser without needing to com ...

Location of Custom HTML Widget in Django-Dashing

I've encountered a dilemma while using the Django-Dashing framework, specifically regarding the placement of my HTML file for a custom widget. I have meticulously configured the code in my dashboard.html file to ensure proper loading. {% extends &apo ...

What is the best way to refresh the user interface while executing a lengthy operation in AJAX/Javascript?

With a need to call multiple processes in series using synchronous AJAX calls, I aim to display the status of each long-running process upon completion before proceeding to the next. Below is an excerpt from the code that illustrates this concept: var co ...

Specialized function to identify modifications in data attribute value

I have a container with a form inside, featuring a custom data attribute named data-av Here is how I am adding the container dynamically: > $("#desti_div").append("<div class='tmar"+count+"'><div > class='form-group col-md-6 ...

Tips for ensuring the Google Maps API script has loaded before executing a custom directive on the homepage of an Angular website

Issue - I am facing issues with Google Maps autocomplete drop-down not working on my website's main page even after parsing and loading the Google Maps API script. The problem seems to be a race condition on the main page of my website, specifically i ...

Change the height of textarea dynamically using jQuery

I am trying to create a comment box similar to Facebook's, where it resizes as text fills it using Expanding Text Areas Made Elegant This is how my view looks: <div class='expandingArea'> <pre><span></span></ ...

Improving the Efficiency of JavaScript/jQuery Code

Currently, I am delving into JavaScript and jQuery. Here is the code snippet that I am working on: $("#hrefBlur0").hover(function() { $("#imgBlur0").toggleClass("blur frame"); }); $("#hrefBlur1").hover(function() { $("#imgBlur1").toggleClass("blur fra ...

Tips for correctly storing an async/await axios response in a variable

I am facing a challenge with the third-party API as it can only handle one query string at a time. To overcome this limitation, I am attempting to split multiple strings into an array, iterate through them, and make async/await axios calls to push each res ...