简体   繁体   English

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

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

I have a helper that prepares an expression like this {{@../../key}}.{{@../key}}.{{@key}} .我有一个助手准备这样的表达式{{@../../key}}.{{@../key}}.{{@key}} How can I execute this expression which is returned by an helper我如何执行这个由助手返回的表达式

Example Obj:示例对象:

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

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

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

Recieved Output: <input name="{{@../../key}}.{{@../key}}.{{@key}}" />接收到的输出: <input name="{{@../../key}}.{{@../key}}.{{@key}}" />

Simple Example Here 简单的例子在这里

This can be solved through a recursive helper.这可以通过递归助手来解决。 Like this:像这样:

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('.');
});

See playground游乐场

Edit: If you really just want the path to some arbitrary depth, then use this version instead.编辑:如果您真的只想要某个任意深度的路径,请改用此版本。

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('.');
});

See playground游乐场

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

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