首页 > 解决方案 > 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包装在另一个模块中,代码针对车把实例运行,如示例脚本中所示。我们正在导出车把实例。

标签: javascriptnode.jshandlebars.jsdeployd

解决方案


该字符串是一个缓冲区

尽管记录typeof了我作为字符串传递的模板字符串readFileAsync但没有传递编码的输出是原始节点缓冲区。

呵呵


推荐阅读