Mustache.js 每个循环都不起作用

Mustache.js each loop not working

我的小胡子模板没有渲染,我不明白为什么。

var output = Mustache.render('{{#languages}} {{@index}} {{locale}} {{/languages}}', '{"languages" : [ { "locale" : "english", "code" : "en" }, { "locale" : "deutsch", "code" : "de" }, { "locale" : "español", "code" : "es" }, { "locale" : "français", "code" : "fr" } ]}');

此输出为空。我还希望索引与每个项目一起呈现。

Demo

一方面,您传递的是字符串而不是对象作为第二个参数。

第一个问题是您应该传递一个对象作为数据,而不是字符串。删除 languages 对象周围的引号。

第二个问题是Mustache 不支持{{@index}} 特殊引用。许多类似 Mustache 的模板系统,例如 Dust.js and Handlebars.js do intrinsically support this, but in Mustache you'll have to write a helper and include it in your data. To do that, see one of the many other Whosebug answers on the topic, such as this one.

Mustache.render() 中的第二个参数是对象。你传递了一个字符串

Mustache.render('{{#languages}} {{@index}} {{locale}} {{/languages}}',  {"languages" : [ { "locale" : "english", "code" : "en" }, { "locale" : "deutsch", "code" : "de" }, { "locale" : "español", "code" : "es" }, { "locale" : "français", "code" : "fr" }, { "locale" : "italiano", "code" : "it" }, { "locale" : "português (Portugal)", "code" : "ptpt" }, { "locale" : "português (Brasil)", "code" : "prbr" }, { "locale" : "Norsk", "code" : "no" }, { "locale" : "日本語", "code" : "jp" }, { "locale" : "中文", "code" : "cn" }, { "locale" : "Русский язык", "code" : "ru" } ]} );