Meteor Cheatsheet Templates

meteor-cheat-sheet

// Meteor - Templates - Blaze:

{{#if Template.subscriptionsReady}}
{{else}}
{{/if}}

currentTemplate = Blaze.renderWithData(Template.templateName, data, document.getElementById('content'));
currentTemplate = Blaze.render(Template.templateName, document.getElementById('content'));
Blaze.remove(currentTemplate);
var help = Blaze.toHTML(Template.helpModal);
var html = Blaze.toHTML(Blaze.With(data, function() { return Template.templateName; }));

// To define a helper function:

Template.templateName.helpers({
  getDefaultEntry: function() {
    return {
      deckId: this.id,
      isQuizzable: 1,
      isPluginApplicable: 1,
      question: '',
      answer: ''
    }
  },
  getEntries: function() {
    return Entries.find({deckId: this.id});
  }
});
Template.templateName.helpers({
  anAttribute: "hi", // in html -> {{ anAttribute }}
  aDynamicAttribute: function(){ // in html -> {{ aDynamicAttribute }}
    return 1+1;
  }
});

// To make a non-reactive helper function:

Template.foo.helpers({
    info: function() {
        return Tracker.nonreactive(function() {
            var user = Meteor.user();
            if(user && user.profile) {
                return user.profile.info;
            } else {
                // return some other appropriate value if the if-statement above
                // is not fulfilled
            }
        });
    }
});

A typical helper function is not reactive unless it returns a reactive data source.
Tracker.nonreactive(func) calls func with Tracker.currentComputation temporarily set 
to null and returns func‘s own return value. If func accesses reactive data sources, these 
data sources will never cause a rerun of the enclosing computation.

// To define a global template helper function:

Template.registerHelper('truncate', function(stringToShorten, maxCharsAmount){
  if(stringToShorten.length > maxCharsAmount){
    return stringToShorten.substring(0, maxCharsAmount) + '...';
  }
  return stringToShorten;
});

// To invoke a template helper function inside a template:

{{templateHelperName parameter1 parameter2}}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License