marianocifre
marianocifre

Reputation: 61

mustache js - Can't access array value using tables

I am having a problem with Mustache.js accessing to the values of a json array and I need some help.

The problem is when I want to access to the values using a table. It always shows [object Object], when it should show the array content.

Below is a working and a non-working example:

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://raw.github.com/janl/mustache.js/0.7.2/mustache.js"></script>
</head>
<body>
<div id="template" style="display:none">
  <p>Works but not what I need:</p>
  <p>{{#numbers}} {{.}} {{/numbers}} </p>
  <p>Doesn't work:</p>
  <table>
      <tr>
        {{#numbers}} <th> {{.}} </th> {{/numbers}}
      </tr>
  </table>
</div>
<div id="rendered"></div>
<script>
var json = {
  "numbers": [ 1, 2, 3 ]
  };
var compiledTemplate = Mustache.to_html($('#template').html(), json).replace(/^\s*/mg, '');
$('#rendered').html(compiledTemplate);
</script>
</body>
</html>

Output is:

Works but not what I need:
1 2 3
Doesn't work:
[object Object] 

Is there any way to solve this problem or to print the object attributes using mustache.js?

The issue was already asked in their issue system, no replies yet: https://github.com/janl/mustache.js/issues/295

Thanks, Mariano.

Upvotes: 2

Views: 1323

Answers (3)

Alex from Jitbit
Alex from Jitbit

Reputation: 60792

I spent a lot of time debugging this.

The problem is $('#template').html(). It returns broken HTML because table markup is malformed (stuff outside <th> is rendered outside the table by browser)

That is why changing to <script> helps

Upvotes: 0

marianocifre
marianocifre

Reputation: 61

Finally, this is what I did.

Replaced the div element template, to a script element:

from <div id="template" style="display:none"> to <script id="template" type="text/x-mustache-template">

And worked as expected =)

Upvotes: 4

Thomas Yang
Thomas Yang

Reputation: 1

Would you like this?

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://raw.github.com/janl/mustache.js/0.7.2/mustache.js"></script>
</head>
<body>
<div id="template" style="display:none">
  <p>Works but not what I need:</p>
  <p>{{#numbers}} {{.}} {{/numbers}} </p>
  <p>Doesn't work:</p>
  <table>
      <tr>
        {{#numbers}} {{{th}}} {{/numbers}}
      </tr>
  </table>
</div>
<div id="rendered"></div>
<script>
var json = {
  "numbers": [ 1, 2, 3 ],
  "th": function () {
    return "<th>" + this + "</th>"
  }
};
var compiledTemplate = Mustache.to_html($('#template').html(), json);
$('#rendered').html(compiledTemplate);
</script>
</body>
</html>

Upvotes: 0

Related Questions