【问题标题】:How to render a template with Twig to string in Nodejs?如何使用 Twig 将模板渲染为 Nodejs 中的字符串?
【发布时间】:2020-08-06 00:42:26
【问题描述】:

我在 Twig(https://www.npmjs.com/package/twig) 中有一个模板,我想让它呈现为字符串。我正在使用 TS。

function getHtml(title: string, message: string): Promise<string> {
  const html = await promisify(renderFile)('./template.twig', {
    filename: 'template.twig',
    settings: {
       title,
       message,
    },
  });
  return html;
}

但承诺始终处于未决状态,即使我使用回调版本也无法获得 HTML。

import Twig from 'twig';
Twig.renderFile('./path/to/someFile.twig', {foo:'bar'}, (err, html) => {
  html; // compiled string
});

通过此调用,不存在默认导出的 TS 警报...

谢谢!

【问题讨论】:

  • 你能不能透露一下你的tsconfig.json
  • 是的:{“compilerOptions”:{“emitDecoratorMetadata”:true,“experimentalDecorators”:true,“outDir”:“./dist”,“allowJs”:true,“target”:“es6 ", "sourceMap": true, "module": "commonjs", "moduleResolution": "node", "resolveJsonModule": true }, "include": ["./src/**/*", "./ src/**/*.json"], "排除": ["node_modules"] }
  • 如果你像node dist/index.js一样在./dist调用你的脚本,你必须小心path/to/twig,所以路径应该与dist相关。
  • 我用ts-node直接在ts中运行
  • 我不确定它是否也会将您的脚本复制到 dist。只需通过在函数开头注销 __dirname 来仔细检查

标签: javascript node.js typescript twig


【解决方案1】:

看起来这个包的类型不正确

尝试使用@ts-ignore 并像这样传递参数:

// @ts-ignore
promisify(renderFile)('./template.twig', {message: 'Hello'})
    .then(html => console.log(html)); // Message: Hello

【讨论】:

  • 什么也没发生 :( 错误不再存在但什么也没发生
  • 确保你的项目有 "@types/node": "^14.0.27", "@types/twig": "^1.12.3", "ts-node": "^8.10 .2", "twig": "^1.15.1", "typescript": "^3.9.7"
  • 并尝试通过 npx ts-node ./main.ts 运行它
  • 如果我在根目录 ts-node index.ts 中运行您的代码一切正常,如果 index.ts 在另一个文件夹中,则没有任何反应 =O
  • 我解决了我的模板路径错误 LOL,感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 2015-12-22
  • 2014-09-13
  • 2012-06-21
相关资源
最近更新 更多