Dan Dascalescu
Dan Dascalescu

Reputation: 151916

Access template instance object properties directly from Spacebars

As the Meteor docs state,

A template instance object represents an occurrence of a template in the document. It can be used to access the DOM and it can be assigned properties that persist as the template is reactively updated. [...] you can assign additional properties of your choice to the object.

How can these properties be accessed from Spacebar templates?

It's cumbersome to have to define helpers that do nothing more than

return Template.instance().myProperty

Upvotes: 1

Views: 512

Answers (3)

khem poudel
khem poudel

Reputation: 587

I think you can use {{#with}}{{/with}}

for example

{{#with getObject}}
<h1>{{prop1}}</h1>
<h2>{{prop2}}</h2>
{{/with}}

and in helper

getObject:function(){
return {prop1:'some text prop1',prop2:'some text prop2'}
}

Upvotes: 0

sdooo
sdooo

Reputation: 1881

Just like @apendua said in comment, you can use global helper, this worked for me:

Template.mainPage.onCreated(function(){
  this.test = new ReactiveVar('stackoverflow');
});

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

and in HTML

{{instance 'test'}}

You could probably use Template.currentData() as well.

Edit

According to this article you can do in HTML something like:

{{Template.instance.test.get}}

so there is no need for global helpers, and it is accessible from Spacebars so no helpers required

Upvotes: 4

FullStack
FullStack

Reputation: 6020

OP wants to access the data directly without any helpers. You will need to store the data in Template.currentData() or Template.parentData(n). Anything in those can be accessed as {{myData}} or {{../myParentData}}, respectively.

Upvotes: 1

Related Questions