Meteor data context, passing array into each Spacebars loop

你离开我真会死。 提交于 2020-01-06 14:44:44

问题


In this Example 2 -- "Passing a data context"

JS

Template.overview.helpers({  
  users: [
    { name: 'David' },
    { name: 'Shaune' }
  ]
});

HTML

<template name="overview">  
  {{> userList users}}
</template>

<template name="userList">  
  {{#each this}}
    {{name}}<br>
  {{/each}}
</template>  

Result

David  
Shaune 

My goal is to pass an array of template names into Template.overview where users is, like so:

<template name="overview">  
  {{#each templateArray }}
    {{> userList this }}
  {{/each}}
</template>

Where templateArray is an array of strings with template names, and this is the name of each template.

Is this possible?

EDIT:

For more depth, consider that I have the following in my helpers

Template.overview.helpers({  
  users: [
    { name: 'David' },
    { name: 'Shaune' }
  ],
  otherUsers: [
    { name: 'Jane' },
    { name: 'Betty' }
  ],
  moarUsers: [
    { name: 'Ben' },
    { name: 'Jerry' }
  ]
});

And I'd like to pass each of these data context into the same template (in this case userLists).


回答1:


You don't need to call anything, you can use this inside helper, like

helper: function(){
   return this; //if you pass string via templateArray
   return this.name; //if you pass object via templateArray
}

Because what you do looks like this but is just wrapped nicely into templates

<template name="overview">  
  {{#each templateArray }}
      {{name}}<br>
  {{/each}}
</template>

I don't know why you have in code double loop, in first loop you pass object and it can't iterate throught it

EDIT

If you wanna just loop throught array of strings, do:

{{#each templateArray}}
       {{this}}<br>
 {{/each}}


来源:https://stackoverflow.com/questions/27682176/meteor-data-context-passing-array-into-each-spacebars-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!