我正在尝试让Handlebars JS显示一个Typescript Map的内容,其中键是字符串,值是对象。为什么下面的代码和模板不工作?代码生成索引号作为键(当它应该是字符串键)和空值。我如何修复它?
import * as fs from 'fs';
import Handlebars from 'handlebars';
function main() {
let template;
try {
const content = fs.readFileSync('template.hbs').toString();
template = Handlebars.compile(content);
}
catch (e) {
}
let map = new Map<string, object>();
map.set("color1", { type: "red"});
map.set("color2", { type: "green"});
map.set("color3", { type: "blue"});
console.log("JSON");
let json = template({map}, { strict: true });
console.log(json);
}
main();
和template.hbs
{
"colors": {
{{#each map}}
"{{@key}}": {
"type": "{{type}}"
},
{{/each}}
}
}
输出为:
JSON
{"colors": {
"0": {
"type": ""
},
"1": {
"type": ""
},
"2": {
"type": ""
},
}
}
1条答案
按热度按时间zyfwsgd61#
手柄不能直接处理Map。它需要一个帮助器方法:
然后,模板使用此处理程序: