I have a helper that prepares an expression like this {{@../../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}}" />
Expected Output: <input name="abc" />
Recieved Output: <input name="{{@../../key}}.{{@../key}}.{{@key}}" />
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.