Meteor: Blaze.Each example

3.1k views Asked by At

How can one use Blaze.Each? For example, I'd like to emulate this:

{{#each Items}}
  {{this}}
{{/each}}

in JS. I need to keep reactivity.

Something like:

Blaze.Each(Items.find(), function(item) {
 console.log(item);
});
2

There are 2 answers

0
ZuzEL On BEST ANSWER

I don't get previous answer

This

html

<template name="yourTemplate">
    <div id="each-area">
    </div> 
</template>

js

Template.yourTemplate.onRendered(function () {
    var renderableContent = Blaze.Each(Collection.find({}), function(){
        return Template.templateToRender;
    });
    Blaze.render(renderableContent, this.find("#each-area"));
});

Is complete equivalent of this:

html

<template name="yourTemplate">
    <div id="each-area">
        {{#each data}}
           {{>templateToRender}}
        {{/each}}
    </div> 
</template>

js

Template.yourTemplate.helpers({
    "data": function(){
        return Collection.find({})
    }
});
7
kaoskeya On
this.autorun(function(){
    var items = Items.find(); 
     _.each(items.fetch(), function(item) {
        console.log(item);
    });
});

This works. It console.logs everytime an Item is added.

w/o underscore and autorun:

Blaze.Each(Data.find().fetch(), function(item){ 
    console.log(item) 
})