javascript - Handlebars.js 中花括号内的变量名
问题描述
我有一个助手可以准备这样的表达式{{@../../key}}.{{@../key}}.{{@key}}
。如何执行由助手返回的这个表达式
示例对象:
{
"a": {
"b": {
"c": 1
}
}
}
例子:
<input name="{{testHelper arg1 arg2}}" />
预期输出:
<input name="a.b.c" />
收到的输出:
<input name="{{@../../key}}.{{@../key}}.{{@key}}" />
解决方案
这可以通过递归助手来解决。像这样:
Handlebars.registerHelper('getPath', function(meta) {
const resolvePath = (node, path=[]) => {
if (node._parent) {
return resolvePath(node._parent, [node.key, ...path]);
}
return [node.key, ...path];
}
return resolvePath(meta.data)
.filter(p => p !== undefined)
.join('.');
});
看游乐场
编辑:如果您真的只是想要任意深度的路径,请改用此版本。
Handlebars.registerHelper('getPath', function(depth, meta) {
const resolvePath = (depth, node, path=[]) => {
if (node._parent && depth > 0) {
return resolvePath(depth-1, node._parent, [node.key, ...path]);
}
return [node.key, ...path];
}
return resolvePath(depth, meta.data)
.filter(p => p !== undefined)
.join('.');
});
看游乐场
推荐阅读
- momentjs - moment 对象在格式化时给出不同的日期
- azure - Azure 应用服务中使用的字体列表是什么
- android - onBackPressed 在隐式意图中不起作用
- html - 我在我的 laravel 项目中使用了一个选择标签,但是当我选择它时,它没有从选项中获取任何值
- amazon-cloudsearch - 无法通过 Java SDK 在 AWS CloudSearch 中上传具有特殊字符的文档
- sql-server - sql server上'='错误附近的语法不正确
- excel - Workbook_BeforeClose 事件上的 Excel 自己的对话框,取消选项
- ios - React Native 0.60 升级:未知类型名称“MutexType”
- reactjs - 可能是比赛条件
- oracle - 如何在表被截断时创建将数据移动到另一个表的触发器