Murali Krishna
Murali Krishna

Reputation: 187

How to pass the data to a template using blaze-layout render?

I tried the following code to pass data to a template and receive it in onCreated() but I cannot access the data.

deviceInfo.js:
BlazeLayout.render('layout',{main:'deviceInfo',stats:'paramstats',attr:"SOME_DATA"});

deviceInfo.html:
{{>Template.dynamic template=stats data=attr}}

paramstats.js:
Template.paramstats.onCreated( () => {
    console.log("onCreated");
    console.log("Data is:",this.data.attr);
});

But I get TypeError: Cannot read property 'attr' of undefined. where am I going wrong?

Upvotes: 2

Views: 1759

Answers (3)

Armen Babakanian
Armen Babakanian

Reputation: 2305

I am using Meteor 1.4.# and I was able to retrieve the parameters like so:

BlazeLayout.render("page", { 
    params: ['fullscreen', 'route']
});

// page.js

Template.page.onCreated(function() {
    let params = this.data.params();
    console.log(params);
}

Upvotes: 1

Michel Floyd
Michel Floyd

Reputation: 20227

Not quite sure why you're using two levels of indirection. BlazeLayout.render() is giving you one level and then you're using a dynamic template within that? Why not directly render the template you ultimately want using BlazeLayout.render()?

In any case, you're dereferencing your data context indirectly.

In the BlazeLayout.render() call you're setting the attr variable to some value.

Then in your dynamic template you're using data=attr but this means that inside your template helpers that this is going be have the value of attr. There will be no data subkey added automatically.

You don't show the value that you're setting for attr so it's not even clear that you have an attr subkey in your attr variable, that would also be confusing to anyone else who ever tries to debug your code.

@khang is correct about not using the arrow function syntax in onCreated(), try:

Template.paramstats.onCreated(function(){
    console.log("onCreated");
    console.log("Data is:",this);
});

this should have whatever value you stuffed into attr in your BlazeLayout.render()

Upvotes: 0

kkkkkkk
kkkkkkk

Reputation: 7738

You need to use the normal function syntax for onCreated callback. Arrow function will bind the context of your function to the outer scope automatically, it is the cause of your problem. Try this:

Template.paramstats.onCreated(function() {
    console.log("onCreated");
    console.log("Data is:",this.data.attr);
});

Upvotes: 1

Related Questions