Venkat
Venkat

Reputation: 841

How to Load Array values to Template Variable in Meteor JS?

How to Load Array values to Template Variable in Meteor?. Please see the below code and suggest me what to do?

HTML Code :

 <template name="header">
 <div class="header">
    {{#each alphabets}}
       <div class="alphabets">{{this}}</div>
    {{/each}}
 </div>
</template>

JS Code :

 //the below array values are load dynamically above template
 var Alphas = ['ALL',
              'A', 'B', 'C', 'D','E', 'F',
              'G', 'H', 'I', 'J','K', 'L',
              'M', 'N', 'O', 'P','Q', 'R',
              'S', 'T', 'U', 'V','W', 'X',
              'Y', 'Z'
              ]

        Template.header.alphabets = function (i)
         {
           return Alphas[i];
         };

Upvotes: 2

Views: 7699

Answers (4)

ParTYZane
ParTYZane

Reputation: 231

Template.header.alphabets

depricated.

Use Template.templateName.helpers insteed.

<template name="newTextLabel">
  {{#each textType}}
  <span class="label label-primary pull-right">{{this}}</span>
  {{/each}}
</template>

Template.newTextLabel.helpers ({
    textType: function() {
    var xxx = ZZZ.findOne(this);
    return xxx.tag;
}
})

collection ZZZ has documents with array named 'tag'

Upvotes: 1

Melih
Melih

Reputation: 463

Instead iterate over an array you can use all array values as below

<template name="alphabet-template">
  {{#if alphabets}}
    <div class="post-alphabet">
      <p> Element: {{alphabets}}</p>
    </div>
  {{/if}}
</template>

Upvotes: 0

Serkan Durusoy
Serkan Durusoy

Reputation: 5472

Template html:

<template name="header">
  <div class="header">
    {{#each alphabets}}
      <div class="alphabets">{{this}}</div>
    {{/each}}
  </div>
</template>

Template js:

var Alphas = ['ALL',
              'A', 'B', 'C', 'D','E', 'F',
              'G', 'H', 'I', 'J','K', 'L',
              'M', 'N', 'O', 'P','Q', 'R',
              'S', 'T', 'U', 'V','W', 'X',
              'Y', 'Z'];

Template.header.alphabets = function() {
  return Alphas;
};

I tested this and it works.

Basically, you can pass arrays just like cursors and each will iterate them both the same.

If you have key/value pairs in your array, you can address them just like mongo documents as well.

Upvotes: 10

Hubert OG
Hubert OG

Reputation: 19544

Helpers usually return the whole array, not individual indexed element. Looping is done by the {{#each}} block. So your helper shouldn't have the parameter, and look simply like that:

Template.header.alphabets = function () {
    return Alphas;
};

And you call it directly, with no reference to Alphas (since your template doesn't know that variable).

{{#each alphabets}}
    <div class="alphabets">{{this}}</div>
{{/each}}

 


This is pretty natural when you think about it this way: for #each element of alphabets, print a div containing this element.

Upvotes: 1

Related Questions