Storing/creating Blaze templates within a namespace


#1

Is there any way to create and store a template without using the global ‘Template’ var? Or at least to create a reference to the global var so we don’t have to use it directly? I’d like to create templates in different local packages and store them in the app’s namespace, so instead of

{{> commentsList}}
{{> commentsFooter}}

I’d like to be able to do something like

{{> myapp.templates.comments.list}}
{{> myapp.templates.comments.footer}}

and to assing helpers like

myapp.templates.comments.list.helpers{{ helper: fn() });

#2

I helped on an app in coffeescript where they did something similar, here’s a snippet you could use (converted from CS, so might contain errors, but you should be able to get the idea):

App.template = function(name, options) {  
  var meteorTemplate = Template[name];
  
  if (options.helpers != null) {
    meteorTemplate.helpers(options.helpers);
  }
  
  if (options.events != null) {
    var processedEvents = {};
    var ref = options.events;
    
    for (event in ref) {
      var func = ref[event];
      processEvent(processedEvents, event, func);
    }
    
    meteorTemplate.events(processedEvents);
  }
  
  var ref1 = ['created', 'rendered', 'destroyed', 'onCreated', 'onRendered', 'onDestroyed'];
  var results = [];
  
  for (var i = 0, var len = ref1.length; i < len; i++) {
    var method = ref1[i];
    if (options[method] != null) {
      results.push(meteorTemplate[method] = options[method]);
    } else {
      results.push(void 0);
    }
  }
  
  return results;
};

The template js looks like this:

App.template('someTemplateName', {
  helpers: {

  },
  events: {

  }
});

This way you can cast templates in objects etc. Should work within a nested object for example.

Hope it’s useable.