Search code examples
meteormeteor-helper

Use ReactiveVar in {{each}} helper


I have a ReactiveVar in my helper which returns a number of photos to be placed in a template

photoCount:->
    Template.instance().rvPhotoCount.get()

Now I need to reactively populate my html with a # of img returned by photoCount. I tried using {{each photoCount}}<img> but receive an error {{#each}} currently only accepts arrays, cursors or falsey values.
How do I tackle this?


Solution

  • The {{#each}} operator is used for iterating over a list of things, such as, in your case, the list of your images.

    Currently you are passing {{#each}} the number of images you have. And each does not know how to iterate over a single number!

    If you want to display each of the images, you should pass each the image list itself, in the form of an array or cursor:

    {{#each images}}<img src={{src}} />{{/each}}
    

    If you just want to display the number of images, just use {{photoCount}}!

    <p>There are {{photoCount}} images.</p>
    

    If you just want to print a number of the same "static" img, you'll have to pre-process the array in your helper:

      photoCount: function(){
        var countArr = [];
        var count = Template.instance().rvPhotoCount.get();
        for (var i=0; i<count; i++){
          countArr.push({});
        }
        return countArr;
      }
    

    And use {{#each}} on it. Sadly, Meteor is very limited in terms of built-in templating functionalities.