An easy way to reference template instance within template code

Since the Template.instance() construct was first introduced to Blaze we have all been tying template state variables to template instances:

Template.myTemplate.onCreated(function () {
  this.state = new ReactiveVar();
});

because they could be finally accessed from helpers:

Template.myTemplate.helpers({
  state: function () {
    return Template.instance().state.get();
  },
});

That’s fine but it would be even better if we could omit creating that helper and simply write:

<template name="myTemplate">
  <p>my state is {{Template.instance.state}}</p>
</template>

Of course I can workaround this by defining a global helper:

 Template.registerHelper('$instance', function () {
   return Template.instance();
 });

in which case I should be able to use {{$instance.state.get}} in myTemplate code. But I don’t like this solution because it’s not standard and .get is redundant.

Is there any other simple solution which does not involve messing up with meteor code?

Template.registerHelper('var', function (variable) {
  return Template.instance()[variable].get()
});

3 Likes