javascript - Handlebars.compile 抛出异常'错误:您必须将字符串或 Handlebars AST 传递给 Handlebars.compile。你通过了 ...'
问题描述
前提
我们在后端 nodejs 应用程序中运行了把手,用于模板化发送的各种消息。
Handlebars.compile 抛出此异常(从部分编译模板时)
Error: You must pass a string or Handlebars AST to Handlebars.compile. You passed <html>
<head>
... extremely long markup
at Object.compile (/Users/guscrawford/rollick-management-console/deployd/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:501:11)
at HandlebarsEnvironment.hb.compile (/Users/guscrawford/rollick-management-console/deployd/node_modules/handlebars/dist/cjs/handlebars.js:39:40)
at Object.invokePartialWrapper [as invokePartial] (/Users/guscrawford/rollick-management-console/deployd/node_modules/handlebars/dist/cjs/handlebars/runtime.js:71:44)
... additional stack trace through to dpd, bluebird etc.
无法通过隔离复制
继续尝试设置一个废品项目:
yarn add handlebars handlebars-helper-ternary handlebars-helpers handlebars.numeral
然后在 nodejs 中运行这个脚本:
const handlebars = require('handlebars'),
numeralHelper = require('handlebars.numeral'),
ternaryHelper = require('handlebars-helper-ternary'),
helpers = require('handlebars-helpers')({
handlebars: handlebars
});
console.log(`Testing...`);
const base = `
<html>
<body style="font-family:'Segoe UI', Tahoma, Geneva, Verdana, 'sans-serif'; font-size: larger;">
{{>@partial-block }}
<td style="text-align: center; padding: 24px;">
Copyright 2018 My Company, Inc. All rights reserved.
</body>
</html>
`;
const inner = `
{{#>base}}
{{subscriber.name}},
{{member.name}} has received a notifier from {{subscriber.name}}.
Click the link below to review!.
<a href='{{link}}'>Go!</a>
Thank you,
My Company
{{/base}}
`;
numeralHelper.registerHelpers(handlebars);
handlebars.registerHelper('ternary', ternaryHelper);
handlebars.registerHelper("moduloIf", function (index_count, mod, block) {
if (index_count > 0 && parseInt(index_count) % (mod) === 0) {
return block.fn(this);
} else {
return block.inverse(this);
}
});
handlebars.registerHelper("substitute", function(a, options) {
try {
function index(obj,i) { return obj ? obj[i] : {} }
let data = a.split('.').reduce(index, this);
if (data && typeof data === 'string') return data;
else return options.fn(this);
} catch (e) {
console.log('substitute helper:' + e);
}
});
handlebars.registerPartial('base',base)
var output = handlebars.compile(inner)({name:'Gus'});
console.log('Output:');
console.log(output)
进一步考虑
实际上,我们将车把require
包装在另一个模块中,代码针对车把实例运行,如示例脚本中所示。我们正在导出车把实例。
解决方案
该字符串是一个缓冲区
尽管记录typeof
了我作为字符串传递的模板字符串,readFileAsync
但没有传递编码的输出是原始节点缓冲区。
呵呵
推荐阅读
- javascript - 显示和打开引导模式
- javascript - 标头中不包含授权标头
- angular - 单击Angular 5中其他组件的复选框时更新组件数据
- c# - 错误:输入字符串的格式不正确
- bash - 在函数内的直到语句处扩展“$@”
- php - 存储和公共之间的 Laravel Symlink 不起作用?
- android - 从 1.0.2 到 1.1.0 的约束布局库更新出错 (Guideline.getAnchor)
- magento - 已弃用:__autoload() 已弃用,在 magento cd 1.9 上使用 spl_autoload_register()
- xml - XML 签名中 KeyInfo 的用途
- ios - 如何在swift4中的scrollView上设置admob