首页 > 解决方案 > Handlebars.js 中花括号内的变量名

问题描述

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

示例对象:

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

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

预期输出: <input name="a.b.c" />

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

简单的例子在这里

标签: javascripthandlebars.js

解决方案


这可以通过递归助手来解决。像这样:

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

游乐场


推荐阅读