繁体   English   中英

Handlebars.js 中花括号内的变量名称

[英]Variable name inside curly braces in Handlebars.js

我有一个助手准备这样的表达式{{@../../key}}.{{@../key}}.{{@key}} 我如何执行这个由助手返回的表达式

示例对象:

{
    "a": { 
        "b": { 
            "c": 1 
             }
       }
}

示例: <input name="{{testHelper arg1 arg2}}" />

预期输出: <input name="abc" />

接收到的输出: <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('.');
});

游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM