How can I register a callback to be invoked when a template is re-rendered?

So, you have two templates: gallery and image:

<template name="gallery">
  <div id="gallery">  
    {{#each this}}
      {{> image}}
    {{/each}}
  </div>
</template>
<template name="image">
  <div class="image">        
        <img src="{{imgUrl}}" />
  </div>
</template>

Basically, a container template for all the pictures, and then a template for each picture. In your JS file, you would have something like:

var $gallery;

var initMasonry = function($imgs) {
  if ($gallery) {
    $gallery.masonry({
      itemSelector : '.image'
    });
  }
};

var debouncedRelayout = _.debounce(function() {
  if ($gallery) {
    $gallery.masonry();  
  }
}, 200);

Template.gallery.onRendered(function() {
  $gallery = $(this.find('#gallery'));
  var $imgs = this.$('.image');

  $gallery.imagesLoaded(function() {
    initMasonry($imgs);
  });
});

Template.image.onRendered(function() {
  var $imgs = this.$('.image');
  if ($gallery && $imgs) {
    $imgs.imagesLoaded(function() {
      $gallery.masonry('appended', $imgs[0]);
      debouncedRelayout();
    });
  }
});

Here you have rendered callback for the gallery that will first initialize masonry. But this will only work for the images that are already there. So what you need to do is have a rendered callback on the image template that adds the image to the masonry object, and then does a re-layout on it. To prevent the re-layout from being called a bunch of times (which will happen when it first gets populated) you debounce the method. This example only uses 200 milliseconds… you could probably increase the time here.

The tricky part is when an image gets removed. Here you have to keep track of each image as it gets added, then when the template gets destroyed, you have to add it back to the DOM, tell masonry to remove it, then do a debounced re-layout again.

I don’t know if the code above works as is (I had to extract it from a project that contains other stuff that wouldn’t make sense to show), but it should at least give you an idea of how to go about doing it.