How to get an array value at index using Handlebars.js?

后端 未结 2 1472
小鲜肉
小鲜肉 2020-12-14 04:04

Say I have JSON:

{
userinput: [
    {name: \"brian\", \"value\": \"i like pies\"},
    {name: \"susan\", \"value\": \"memes are stupid\"}
],
feedback: [
             


        
相关标签:
2条回答
  • 2020-12-14 04:13

    This can be accomplished using the lookup helper:

    The lookup helper allows for dynamic parameter resolution using Handlebars variables. This is useful for resolving values for array indexes.

    So the template for your example would look like this:

    {{#each userinput}}
        <td>{{name}}</td>
        <td>{{value}}</td>
        <td>
            {{#with (lookup ../feedback @index)}}
                {{value}}
            {{/with}}
        </td>
    {{/each}}
    
    0 讨论(0)
  • 2020-12-14 04:20

    I guess you will have to write a block helper for this, as it seems @index can only be used as a stand-alone.

    I modified the "list" example, to allow a template like this: "{{#list userinput feedback}}<td>{{name}}</td><td>{{value}}</td><td>{{@feedback.value}}</td>{{/list}}". The implementation is like this, accepting two parameters "input" and "feedback" (plus the standard "options").

    Handlebars.registerHelper('list', function(input, feedback, options) {
      var out = "", data;
    
      // iterate over the input
      for (var i=0; i<input.length; i++) {
        if (options.data) {
          data = Handlebars.createFrame(options.data || {});
    
          // add "feedback" item to the current frame's data
          data.feedback = feedback[i];
        }
    
        out += "<tr>" + options.fn(input[i], { data: data }) + "</tr>";
      }
    
      return out;
    });
    

    Here's the Fiddle.

    0 讨论(0)
提交回复
热议问题