Transforming a JSON array into Mustache notation

I'm struggling to integrate the data from my JSON array into my Mustache template. After spending hours on this task, I'm still unclear about what's missing or possibly overwhelming the code.

It's important to mention that I need to utilize let instead of var for this specific assignment.

Below is the code snippet:

HTML:

<script id="mustacheTemplate" type="x-tmpl-mustache">
<ul id="output">
{{#items}}
    <li>{{title}}{{description}}</li>
{{/items}}
</ul>
</script>

JSON:

{ "items": [
    {"title": "Mulan",
    "description": "Based on the Chinese legend of Hua Mulan, and was Disney's 36th animated feature."
    },
    {"title": "Beauty and the Beast",
    "description": "An adaptation of the fairy tale about a monstrous-looking prince and a young woman who fall in love."
    },
    {"title": "Aladdin",
    "description": "Aladdin is a street-urchin who lives in Agrabah, a large and busy town, long ago with his faithful monkey friend Abu."
    ]}
}

Javascript:

console.log($);


$(document).ready(function() {

    $.getJSON('../data/content.json', result);

    function result (data, status){
        console.log(data);

        let template = $("#mustacheTemplate").html();

        let content = data.items;

        let output = Mustache.render(template, content);
        console.log(output);

        $('#output').html(output);
    });
});

Answer №1

When passing the render function, make sure to pass your data instead of using data.item

In this code snippet, I have commented out your

$.getJSON('../data/content.json', result);

This can be a useful guide for you

function result (data, status){
      data={ "items": [
    {"title": "Mulan",
    "description": "Based on the Chinese legend of Hua Mulan, and was Disney's 36th animated feature."
    },
    {"title": "Beauty and the Beast",
    "description": "An adaptation of the fairy tale about a monstrous-looking prince and a young woman who fall in love."
    },
    {"title": "Aladdin",
    "description": "Aladdin is a street-urchin who lives in Agrabah, a large and busy town, long ago with his faithful monkey friend Abu."}
    ]
};
        //console.log(data);

        let template = $("#mustacheTemplate").html();
//console.log(template)
        let content = data;

        let output = Mustache.render(template, content);
        //console.log(output);

        $('#output').html(output);
        }
$(document).ready(function() {

    //$.getJSON('../data/content.json', result);

    
   result(1,5);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
<script id="mustacheTemplate" type="x-tmpl-mustache">
<ul>
{{#items}}
    <li>{{title}}{{description}}</li>
{{/items}}
</ul>
</script>

<div id="output"></div>

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

Making changes to the Array.prototype leads to errors in another JavaScript library

I am currently utilizing Crystal Reports within ASP.NET webforms to display some report files. The framework produces javascript for the UI functionality. If I modify the array prototype in any way, the script mentioned above throws 2 errors. These errors ...

Using jQuery to Post JSON

I need help with implementing an ajax call that sends data in JSON format. There seems to be a syntax error in my code. For example: var string_json='{"usr":{"name":"john","surname":"do"}}'; $.ajax({ url:"myurl",type:"post",data:{user:JSON.strin ...

Apply the cursor property to the audio element and set it as a pointer

I have a question: how can I apply a cursor style to my <audio> controls? When I try to add them using CSS, the cursor only appears around the controls and not directly on the controls themselves. Below is the code snippet: <audio class="_audio" ...

CSS struggles after implementing conditional checks in return statement for an unordered list

I'm encountering a CSS issue with the header section. When I include the following code snippet in my code to display a tab based on a condition, the entire header list doesn't appear in a single horizontal line: <div> {isAdmin(user) ? ...

The functionality of event.charCode is ineffective in Firefox

I'm in a dilemma with restricting my text field to only accept numbers. Currently, I have the following code snippet: onkeypress="return (event.charCode >= 48 && event.charCode <= 57)" The issue arises when I attempt to delete (using b ...

Having trouble with table sorting in Jquery?

I am a beginner in the realm of Jquery and web programming. Recently, I attempted to implement the tablesorter jquery plugin for one of my projects but encountered issues with making it work properly. In search of a solution, I turned to Stack Overflow. C ...

Removing Files from an ASP.NET MVC 5 Website

Check Out the Code @using(Html.BeginForm("Edit", "Products", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() < div class = "form-horizontal" > @Html.ValidationSummary(tr ...

Why does an Android/Sencha/PhoneGap ajax request to a local PHP file result in the entire code being returned

Is there anyone who can assist me with this issue? I am using phonegap to run a sencha app on an android phone. In my code, I am making an ajax call to a local php file to check if a certain file exists... var myRequest = Ext.Ajax.request({ ...

Assistance required for JavaScript with Image and Hyperlinks

In the provided code snippet, I have included a javascript onclick function to the image tag. After clicking the image and then going back, the page remains on the current page rather than returning to the original page. Is there a way to prevent this beha ...

I don't understand why I keep receiving the error message "Cannot read property 0 of undefined" even though the object clearly exists and I am attempting to access it within the correct scope

Here is a function example: (function iterate(index) { var obj = { 0:{name:"John Doe"}, 1:{age: 30}, 2:{years: 5} }; setTimeout(function() { //code ... }, (obj[0][years]*1000) ); )(0); Encountering an error in the second last line myscript. ...

"Exploring the wonders of D3 paired with bidirectional data binding

I am seeking information on the most effective methods and solutions for utilizing data driven documents with two-way AJAX data bindings. Specifically, I am interested in how d3 can be seamlessly integrated with frameworks that support two-way data binding ...

jQuery can detect changes in component variable values and automatically update the input text accordingly

Whenever elements A, B, or C undergo changes, they simultaneously affect the attributes of filename.a, filename.b, and so forth. However, the input value is set only once. Is there a method to ensure that the input text value updates whenever the underlyi ...

Tips for transferring data from a nested component's state to its parent component

I am facing a challenge in extracting the state value from one component to another when clicking on a tag. The goal is to append the value of the clicked tag to a list state in the Form component. Can someone suggest a simple approach to achieve this? T ...

Modify the DOM at a later time once the images have loaded. This particular action is being executed within the context of an

main.ts myFunction(){ this.service.getData().subscribe( response => { this.handleData(response); }, error => console.log(error), () => console.log('request done') ...

Is it possible to hide and reveal specific form elements based on the selection of a checkbox?

Having issues with the code provided below, it's not working as expected. Can you help me figure out what I might be missing? HTML: <input id="id_code_col" type="checkbox" name="code_col"></input> SCRIPT: $(document).ready(function(){ ...

Restricted PHP file upload capabilities

Recently, I encountered an issue with an ajax form while trying to upload a 30MB PDF file. Everything works smoothly when uploading files up to 10MB, but the problem arises when attempting to upload larger files. I noticed that the file is partially upload ...

Issue with Click event not functioning properly following an ajax request in a dynamic element within the Backbone framework

I have successfully implemented a dynamic popup in my Backbone.view through the click of a button: var Section = Backbone.View.extend({ className: 'sqs-frontend-overlay-editor-widget-section', events:{ 'click .sqs--section--control__ed ...

Ajaxload script for mouseover events

I am working on implementing a mouseover event for images displayed on a webpage to show a brief summary of the image in a container called "contentarea". As a newbie in coding, I apologize for any shortcomings. Below is the code I've created, but I&a ...

executing certain code in a JavaScript file for Internet Explorer 9 compared to all other web browsers

As I analyze this single line of code, my goal is to create a conditional statement that executes different actions based on whether the browser is Internet Explorer 9 or not. Here's the code snippet: ('.fa-phone, .bg-darkPink').parent().on ...

Accessing Form Data as an Array in a Single Page Application

I'm currently in the process of developing a single-page PHP application and I'm experimenting with submitting the form using ajax .post() instead of the traditional form submission that redirects to another page. However, I'm experiencing d ...