我正在开发我的第一个Ember.js应用程序,但在连接所有的点时遇到了一些问题。如果我能看到给定handlebars模板中所有可用的变量,那将非常有帮助。
有一个相关的问题,但您必须知道作用域中的变量:How do I add console.log() JavaScript logic inside of a Handlebars template?
我怎样才能输出所有的变量?
发布于 2020-11-09 14:29:10
您可以通过利用Handlebars.parseWithoutProcessing
来实现这一点,它接受输入模板字符串。如果使用TypeScript,则返回特定类型的hbs.AST.Program
。您可以只过滤moustache语句,然后遍历这些语句以获得变量名。
此方法还支持Handlebars,因此您可以获取该对象的键,但正因为如此,此函数有点复杂,因为您需要在moustache语句上检查不同的属性:
/**
* Getting the variables from the Handlebars template.
* Supports helpers too.
* @param input
*/
const getHandlebarsVariables = (input = '') => {
const ast = Handlebars.parseWithoutProcessing(input);
return ast.body
.filter(({ type }) => type === 'MustacheStatement')
.map((statement) => statement.params[0]?.original || statement.path?.original);
};
以下是TypeScript版本,由于条件属性的缘故,该版本有点涉及,但可以帮助更多地解释类型:
/**
* Getting the variables from the Handlebars template.
* Supports helpers too.
* @param input
*/
const getHandlebarsVariables = (input: string): string[] => {
const ast: hbs.AST.Program = Handlebars.parseWithoutProcessing(input);
return ast.body.filter(({ type }: hbs.AST.Statement) => (
type === 'MustacheStatement'
))
.map((statement: hbs.AST.Statement) => {
const moustacheStatement: hbs.AST.MustacheStatement = statement as hbs.AST.MustacheStatement;
const paramsExpressionList = moustacheStatement.params as hbs.AST.PathExpression[];
const pathExpression = moustacheStatement.path as hbs.AST.PathExpression;
return paramsExpressionList[0]?.original || pathExpression.original;
});
};
我做了一个Codepen来说明这一点。本质上,给定以下模板:
Hello, {{first_name}}! The lottery prize is {{formatCurrency prize_amount}}! Good luck!
它将使用window.prompt
来询问用户的姓名和奖金金额。该示例还实现了帮助器formatCurrency
。你可以在这里看到:https://codepen.io/tinacious/pen/GRqYWJE
https://stackoverflow.com/questions/19800602
复制相似问题