2

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];
         };
0

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1
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'

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.