mustache js - 无法使用表访问数组值

时间:2013-02-16 00:44:33

标签: javascript templates mustache

我遇到Mustache.js访问json数组值的问题,我需要一些帮助。

问题是当我想使用表访问值时。它始终显示[object Object],何时应显示数组内容。

以下是一个有效且无法运作的例子:

<!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>

输出是:

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

有没有办法解决这个问题或使用mustache.js打印对象属性?

问题已在他们的问题系统中提出,尚无回复: https://github.com/janl/mustache.js/issues/295

谢谢, 马里亚诺。

3 个答案:

答案 0 :(得分:4)

最后,这就是我所做的。

将div元素模板替换为脚本元素:

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

按预期工作=)

答案 1 :(得分:0)

你想要这个吗?

<!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>

答案 2 :(得分:0)

我花了很多时间调试它。

问题是$(function () { let i = 0; $(".grey").click(function () { if (i !== 5) { // alert('Kasten ausgewaehlt'); $(this).css('background-color', 'red'); i++; } else { alert('Kasten konnte nicht ausgewaehlt werden'); } }); }); 。由于表格标记的格式不正确($('#template').html()之外的内容在浏览器中呈现在表格外部),因此它返回的HTML格式不正确

这就是为什么更改为<th>会有帮助的原因