Is there a way to display this JSON data using mustache.js without needing to iterate through a

Here is the JSON data:


        var details = [
            {
                "event": {
                    "name": "txt1",
                    "date": "2011-01-02",
                    "location": "Guangzhou Tianhe Mall"
                }
            },
            {
                "event": {
                    "name": "txt2",
                    "date": "2011-01-02",
                    "location": "Guangzhou Tianhe Mall"
                }
            },
            {
                "event": {
                    "name": "txt3",
                    "date": "2011-01-02",
                    "location": "Guangzhou Tianhe Mall"
                }
            }
        ];
    

And this is my mustache template:


        {{#event}}
            <div>
                <h2>{{name}}</h2>
                <span>on {{date}}</span>
                <p>{{location}}</p>
            </div>
        {{/event}
    

The current template code above does not work. I am now trying to figure out a way to make it work without using a loop:


        var output = Mustache.render(template, details);
    

Is there a more efficient method to achieve this without the need for a loop?

Answer №1

Here is a different approach using mustache templates to achieve the same outcome. Start by organizing your data like this:

 var info = {info: [
    {
        "event": {
            "name": "txt1",
            "date": "2011-01-02",
            "location": "Guangzhou Tianhe Mall"
        }
    },
    {
        "event": {
            "name": "txt2",
            "date": "2011-01-02",
            "location": "Guangzhou Tianhe Mall"
        }
    },
    {
        "event": {
            "name": "txt3",
            "date": "2011-01-02",
            "location": "Guangzhou Tianhe Mall"
        }
    }
]};

Next, structure your template code like this:

{{info}}
{{#event}}
<div>
<h2>{{name}}</h2>
<span>on {{date}}</span>
<p>{{location}}</p>
</div>
{{/event}
{{/info}}

I hope this provides a helpful alternative solution.

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

Implementing the ability to add and remove classes in JavaScript

I am trying to implement an add or remove class feature in JavaScript, but I'm facing some issues with it. Below is the code snippet I have: if (window.location.hash == "#/profile/"){ document.getElementById("tabMenu").removeClass("bottomTa ...

Preserve a data point without causing any alterations

I am working with a device that continuously sends values until it is stopped. These values are then saved inside an array. deviceMonitoring( device2 ){ // In this function, I populate the arrayTimestamp and then copy the first value. this.arrayElement = t ...

Fixing Laravel 5.2 and jQuery validation issue: Accessing a property from a Non-Object

Currently, I am utilizing the jQuery validation plugin to check whether a username already exists or not. The documentation regarding the validation plugin states: The server-side resource is accessed through jQuery.ajax (XMLHttpRequest) and receives k ...

Tips for efficiently handling multiple form inputs using PHP

As part of my project, I am designing an admin panel for a distribution company. They have specifically requested a feature where they can input orders for all clients through a single page. To meet this requirement, I have created a dynamic form that gene ...

The AMP HTML file is unable to load due to the robots.txt file on https://cdn.ampproject.org restricting access

I've been trying to fetch and render my AMP HTML files individually, but they all seem to be encountering the same issue. According to the Search Console report, it says "Googlebot was unable to access all resources for this page. Here's a list: ...

After being redirected from another page using history() in React, the state is initially set to null but later gets updated to the correct value - Firebase integration

After logging in and being redirected to the profile page, I encounter an error that says 'Unhandled Rejection (TypeError): Cannot read property 'email' of null'. How can I ensure that the state is set before proceeding with any additio ...

sending numerous ajax requests and they all seem to be returning identical results

When firing multiple ajax requests using the setinterval() function, I noticed that both requests are bringing back the same information from another page. Here is the JavaScript code: function views() { setInterval(function(){var xmllhttp //alert ...

javascript accessing an external variable inside ajax function

I have implemented dajaxice to fetch a json attribute that I want to make global. However, I am facing an issue where my global variable is always showing up as "undefined": var recent_id; $(function(){ recent_id = Dajaxice.ticker.get_home_timeline(ge ...

Unable to display content on the ejs file

Currently, I have been diving into the world of node.js and exploring how to manipulate data by writing and reading from JSON files. It has been an interesting journey so far; however, I encountered a hiccup. Specifically, when attempting to post new data ...

Updating a React JS State using a Parameter

Is it feasible to develop a function that accepts a parameter (either a string of the state name or the actual state) and then assigns the state related to the parameter? SetState(x) { // Suppose x can be any state we have already defined (it sh ...

"Troubleshooting: Why is my AngularJS ng-click not triggering the function

My custom directive fetches a navigation block from a webservice call. I am attempting to click on a navigation link that has an "ng-click" attribute set, which should call the specified function. However, the function is not being executed. Below is my r ...

Positioning a Three.js static CSS2DObject with respect to the camera's perspective

I am currently working on a unique program visualizer that utilizes Three.js to showcase various aspects of a program to the user. One crucial feature of this visualizer is allowing users to click on specific objects to view additional information about th ...

Utilizing ReactJS for Web Development with Enhanced Data Insights from Google

Utilizing Google Analytics and various tools, I've encountered an issue with the development of ReactJS. My goal was to collect analytics data from my website by using react-helmet to dynamically change the title and the HTML lang parameter based on t ...

Exploring ways to cycle through dynamically loaded checkboxes with AJAX?

I'm looking to apply a similar function to checkboxes that are loaded dynamically via AJAX: $('input:checkbox').each(function() { $(this).hide(); alert("hi"); $('<div class="checkbox-fx"><div class="che ...

Double Ajax calls being made in Laravel application

I am working on a Laravel application for managing tasks. The application has a form with four fields: one for the CSRF token, two hidden fields for IDs, and an input field to capture the task title. For submitting the form, I have implemented AJAX. Howev ...

Maintaining a security token across multiple requests

A prototype application is being developed with the following features: An HTML website integrated with knockoutjs Communication with Web API services using jQuery/Ajax The goal is to restrict access to services only to authorized users. Security measur ...

How to retrieve distinct items from an array using Javascript

If I have the following array of objects: const arr = [{ id: 'A', version: 0, name: 'first' }, { id: 'A', version: 1, name: 'first' }, { id: 'B', version: 0, name: 'second&apo ...

What is the best way to create a JavaScript array after fetching data from an AJAX request that returns a JSON array?

When I make an ajax call that returns JSON data, my goal is to extract and organize this data into a new JavaScript array through looping. This is a snippet of the JSON data returned: { query: [ ], products: 
[ 
{ title: "title 1", ...

Reset dropdown selection when a search query is made

Currently experimenting with Angular to develop a proof of concept. Utilizing a functional plunker where selecting an option from a dropdown populates a list of items from an $http.get( ). Additionally, there is a search input that should trigger its own $ ...

How does Sizzle JS function?

While investigating the sizzle.js source code for a project, I stumbled upon an interesting discovery. Towards the end of the code, there is a line that reads: window.Sizzle = Sizzle; However, there doesn't seem to be any declaration of a variable n ...