Handlebars无法从Typescript中的Map〈string,object>生成JSON

14ifxucb  于 2023-01-14  发布在  TypeScript
关注(0)|答案(1)|浏览(115)

我正在尝试让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": ""
    },
}
}
zyfwsgd6

zyfwsgd61#

手柄不能直接处理Map。它需要一个帮助器方法:

Handlebars.registerHelper('jsonmap', function (context) {
      return JSON.stringify(Object.fromEntries(context), null, 2);
    });

然后,模板使用此处理程序:

{
    "colors": {{map}}
}

相关问题