[Solved] Template helper: TypeError: Cannot read property 'get' of undefined in "Sub Template"

I can’t use Template.instance() in sub template helper

<template name="main">
  {{> subTemplate}}
</template>

<template name="subTemplate">
  {{hello}}
</template>
-----------------
// Sub Template
subTemplate.onCreated(() => {
  this.hello = new ReactiveVar('Rabbit')
  console.log('onCreated', this.hello.get()) // Work
})

subTemplate.onRendered(() => {
  console.log('onRendered', this.hello.get()) // Work
})

subTemplate.helpers({
  hello() {
      return Template.instance().hello.get() // Don't work
  },
})

Get the error

template helper: TypeError: Cannot read property 'get' of undefined

Please help me

use regular functions in onCreated and onRendered

Arrow functions can’t have the value of this changed, and instead use the this value from the place the function was declared. In your case this is the window instead of the template instance.

Blaze tries to set the value of this to the template instance, but is unable to do so here because not being able to set this is one of the core features of arrow functions

1 Like

@coagmano, You are right :blush:
Very thanks