如何使用 mustache.js 验证小胡子模板?

How to validate mustache template with mustache.js?

我正在使用模块 ejs 来验证来自管理仪表板的 ejs 模板和变量:

try {
  resolve(ejs.render(template, variables))
} catch (error) {
  reject(error)
}

如果这个模板有问题,它会抛出错误,我可以将它发送给客户。

此外,我还有一个小胡子模板需要验证。我正在使用相同的方法:

try {
  resolve(mustache.render(template, variables))
} catch (error) {
  reject(error)
}

但是mustache根本不会抛出错误,如果没有变量,它只是用空字符串替换它。

我该如何解决这个问题?需要正确验证模板。

如果您正在使用 mustache.js, there is no way to have it throw errors on undefined variables, here is an open issue. This seems to be fine according to the Mustache specification

By default a variable "miss" returns an empty string. This can usually be configured in your Mustache library.

所以如果你真的需要验证没有未定义的变量,你将不得不为 Mustache 使用另一个 JS 库(如果有的话,我不确定),或者希望他们添加特征。

我在这个 fork 的库中找到了解决方案。 多亏了 Scott,它才像应该的那样工作。