【问题标题】:Pass an undetermined number of object properties that may be nested传递不确定数量的可能嵌套的对象属性
【发布时间】:2015-03-26 05:16:12
【问题描述】:

我正在尝试编写一个车把助手,我可以在其中传递需要解析的 JSON 字符串,然后获取任何特定属性,不知道可能有多少级嵌套,例如:

Handlebars.registerHelper 'parseJSON', (string, properties) ->
    json = JSON.parse string
    # how can I do: return json[oneProperty][andANestedProperty]

然后将“responseBody”作为我的 JSON 字符串,不知道如何传递它,但我的想法是:

{{parseJSON responseBody [oneProperty][andANestedProperty] }}

【问题讨论】:

    标签: javascript coffeescript handlebars.js handlebarshelper


    【解决方案1】:

    如果你希望能够说出类似的话:

    {{parseJSON json 'p1' 'p2'}}
    {{parseJSON json 'p1' 'p2' 'p3'}}
    

    在你的模板中,你只需要让你的助手接受任意数量的参数。唯一棘手的是 Handlebars properties 参数始终是最后一个。这实际上很容易使用CoffeeScript splat

    Handlebars.registerHelper 'parseJSON', (json, path..., properties) ->
        # path will be an array in here
    

    这将在您的帮助器内的path 数组中为您提供['p1', 'p2']['p1', 'p2', 'p3'] 之类的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 2017-06-21
      • 2019-03-23
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多