Warz
Warz

Reputation: 7746

Pass data to dynamically created template with meteor

Following up on this queston/answer (second answer) Dynamically loading templates in Meteor.js

I have set up a helper in the current displayed template and i am returning the template dynamically. This works great.

Template.template1.helpers({

    dynamicView: function(){
        return Template['dynamic_template']();
    }
})

This ends up showing my html in template 1:

Questions:

  1. How do i pass data to this Template as it's being created, can i do something like this:

    Template['dynamic_template'](data1, jsonData2);

  2. I want the dynamicView helper in template1 to also be dynamic in the sense that it can have a different template based on some other criteria. Can i use a Session here and change the dynamicView return statement to something like this:

    dynamicView: function(){ return Session.get('dynamicTemplate'); }

and somewhere else Session.set('dynamicTemplate', Template['dynamic_template']()); This works, but is it recommended. It's just a string but i am concerned about performance problems and the size of my template being passed reactively

Upvotes: 1

Views: 1654

Answers (1)

Tarang
Tarang

Reputation: 75945

OK I guess ill have to split my answer up:

With 1.

The templates are compiled handlebars templates so you just need to provide a context to them so the handlebars data can be filled up:

data = {name1:value1, name2:value2}
return Template['dynamic_template'](data);

So that {{name1}} and {{name2}} get filled up with value1 and value2 respectively.

With 2.

Yes that should work, you can pass off any data that will give off HTML as a result. For a very detailed videocast have a look at the EventedMind screencast on template functions: http://www.eventedmind.com/posts/meteor-rendering-template-functions

The template system's use case might not be this exactly. You might want to use Meteor.render instead, but it depends on what you want to do.

Despite the Session name, its just a reactive javascript variable so it should be fine with larger strings too to the same that would be used in an ordinary javascript variable

Upvotes: 3

Related Questions