Dealing with special characters in Mustache.js: handling the forward slash

I have a JSON file that contains information about a product. Here is an example of the data:

{
    "products": [
        {
            "title": "United Colors of Benetton Men's Shirt",
            "description": "Cool, breezy and charming – this solid green shirt from United Colors of Benetton is born on the beach. Effortlessly classy, this full sleeved shirt is perfect when worn with faded blue jeans and a pair of shades for a weekend get-together.",
            "quantity": "10",
            "cost": "3.00",
            "brand": "United",
            "image": "catalog/images/img2.jpg",
            "category": "1",
            "popularity": "100"
        }

    ]
}

I am using Mustache.js to display this JSON data in a template like below:

<table class="product-list">
    {{#products}}
    <tr>
        <td> 
            <table class="product">
                <tr>
                    <td class="product-image">
                        <img src"{{image}}" height="150" width="150" />
                    </td>
                    <td class="product-details">
                        <p class="title">{{title}}</p>
                        <p class="description">{{description}}</p>
                        <p class="quantity"><b>Quanity Available: </b>{{quantity}}</p>
                        <p class="cost"><b>Cost: </b>&pound; {{cost}}</p>
                        <p class="brand"><b>Brand:</b> {{brand}}</p>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
    {{/products}}
</table>

Although everything seems to be working well, I am facing an issue with displaying the image properly due to escaped slashes in the URL.

I've tried various methods such as adding backslashes in the JSON file or disabling HTML escaping, but so far I haven't been able to resolve the issue.

If anyone has a solution for correctly displaying the image property, please help!

Edit: The JavaScript code used to generate the template is shown below:

$template = $('#product-template').html();
$renderedHtml = Mustache.render($template, $data);
$('#content').html($renderedHtml);

Answer №1

It appears that using triple mustaches {{{image}}} should make it work. Don't forget to include an equal sign after src.

Check out this example fiddle:

var jsn = {
  "products": [{
      "title": "United Colors of Benetton Men's Shirt",
      "description": "Cool, breezy and charming – this solid green shirt from United Colors of Benetton is born on the beach. Effortlessly classy, this full sleeved shirt is perfect when worn with faded blue jeans and a pair of shades for a weekend get-together.",
      "quantity": "10",
      "cost": "3.00",
      "brand": "United",
      "image": "http://static.cilory.com/26111-large_default/united-colors-of-benetton-men-white-t-shirt.jpg",
      "category": "1",
      "popularity": "100"
    }
  
  ]
};

var t = document.getElementById('template').innerHTML;
var m = Mustache.to_html(t, jsn);
document.getElementById('res').innerHTML = m;
console.log(m);
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.2/mustache.min.js"></script>
<script id="template" type="text/template">
  <table class="product-list">
    {{#products}}
    <tr>
      <td>
        <table class="product">
          <tr>
            <td class="product-image">
              <img src="{{{image}}}" height="180" width="150" />
            </td>
            <td class="product-details">
              <p class="title">{{title}}</p>
              <p class="description">{{description}}</p>
              <p class="quantity"><b>Quanity Available: </b>{{quantity}}</p>
              <p class="cost"><b>Cost: </b>&pound; {{cost}}</p>
              <p class="brand"><b>Brand:</b> {{brand}}</p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
    {{/products}}
  </table>
</script>
<div id="res"></div>

Answer №2

Modify the mustache.js escape function to prevent text from being escaped:

    mustache.escape = function (text) {
      return text;
    };

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

Error: Unable to decode productsTest.json file from application bundle

A notification popped up showing "Build Succeeded". However, on the canvas, an error message displayed saying "Could not view this file - crashed". Subsequently, the application crashed. The issue seems to originate from JSONDecoder.sw ...

Utilizing either Ansible's Jinja templating or Python programming for performing calculations on a constantly

Currently, I'm working with ansible 2.5 and python 2.7 on a project that involves executing calculations on dynamic JSON variables. The variable in question is not fixed and can contain anywhere from 1 to 1000 objects. For example: var: [ { "n ...

What is the best way to use checkboxes to highlight table rows in Jquery Mobile?

I have a Jquery Mobile site with a table. Each table row contains checkboxes in the first cell. I am trying to achieve the following: a) Highlight a row when the user clicks on it b) Highlight a row when the user checks the checkbox I have made progr ...

Transforming jQuery code to pure vanilla Javascript

For my project, I decided to convert my jQuery code into native JavaScript. The goal is to eliminate the dependency on jQuery and achieve the same functionality. The current setup involves two pages - page.html and side.html. The page.html document fetches ...

Transferring JSON encoded information from a controller to a view via ajax within the CodeIgniter framework

After selecting data from the controller, I want to display it on the view using a Bootstrap template. To achieve this, I need to place the following code in my controller: $data['sidebar']='member/dokter/sidebar_psn'; $data['cont ...

Show information in a table based on a unique identifier

I am working with some data that looks like this [ { date: '20 Apr', maths: [70, 80.5, 100], science: [25, 20.1, 30] }, { date: '21 Apr', maths: [64, 76, 80], science: [21, 25, 27] }, ]; My goal is to present ...

The chosen option does not display any information

I am new to databinding an html control using ajax for the first time. After checking and debugging my ajax call, I can see that the data is retrieved successfully, but it does not show up in the select option. My javascript code is positioned at the botto ...

Problem with Ajax causing full-page reload

I currently have a webpage that utilizes JqueryUI-Mobile (specifically listview) in conjunction with PHP and some Ajax code. When the page loads initially, it displays a list generated from a MySQL DB. I want this list to refresh itself periodically witho ...

How can we dynamically navigate to the next line within the Material UI DataGrid component when space is limited?

Currently, I am working with the datagrid component from material ui. I have retrieved some data from a database and am attempting to pass it to the datagrid component. However, I have noticed that certain fields contain long strings which do not fully app ...

Troubleshooting problem with nested object in AngularJS data table

For my project, I am utilizing an angular js datatable and currently trying to access the following object: "finalizedArr":[ { "treaceId":"KYC454353545", "approval":[ ...

Converting the length attribute of a table to a string does not yield any

After grappling with this bug for some time now, I've come up empty-handed in my search for a solution online. Expected Outcome: Upon pressing the create row button, I anticipate a new row being added at the bottom of the table. This row should cons ...

Is there a way to automatically populate the result input field with the dynamic calculation results from a dynamic calculator in Angular6?

My current challenge involves creating dynamic calculators with customizable fields. For example, I can generate a "Percentage Calculator" with specific input fields or a "Compound Interest" Calculator with different input requirements and formulas. Succes ...

Unleash the power of jQuery to leverage two different input methods

Here is the code I'm working with: $('input[type="text"]').each(function(indx){ Right now, this code targets input elements with type "text". But how can I modify it to target both inputs with type "text" and "password"? Any suggestions o ...

Learn how to update image and text styles using Ajax in Ruby on Rails with the like button feature

I'm working on implementing a Like button in Rails using Ajax, similar to this example: Like button Ajax in Ruby on Rails The example above works perfectly, but I'm interested in incorporating images and iconic text (such as fontawesome) instead ...

vue-router default route for children

Currently, I am working on a Vue 2.x application and utilizing vue-router for routing purposes. In certain situations, I need to directly display a child vue. The template structure is as follows: | voice 1 | voice 2 | voice 3 | | submenu 1 | submen ...

The longevity of JQuery features

As I work on setting up an on-click callback for an HTML element to make another node visible, I encountered a surprising realization. The following two statements appeared to be equivalent at first glance: $("#title").click($("#content").toggle); $("#tit ...

Guide on parsing a JSON object in JavaScript

One issue I'm facing is that my controller method returns a string representation of a jsonArray using the jsonArray.toString() function. Below is the corresponding ajax method: function loadPropertyFile(url) { $.ajax({ type: "GET", url: url, ...

For the past two days, there has been an ongoing issue that I just can't seem to figure out when running npm start

After multiple failed attempts, I have exhausted all troubleshooting steps including executing npm clear cache --force, deleting node_modules/ and package-lock.json, followed by running npm install, npm build, and eventually npm run dev. The errors encoun ...

What is the reason for jQuery displaying undefined when attempting to retrieve a custom data attribute using .prop()?

In my dynamic HTML generated by JavaScript, the following code snippet is included: $(".task-status").live("click", function () { alert("data-id using prop: " + $(this).prop("data-id")) alert("data-id using data: " + $(this).data("id")) ...

Building a Dataframe with nested JSON API responses

My current project involves using the Qualtrics API to extract data for analysis at work. The data is returned in JSON format and I want to convert it into a dataframe. I am working within an Alteryx-powered Jupyter notebook and my plan is to export the da ...