Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
177
rated 0 times [  178] [ 1]  / answers: 1 / hits: 25121  / 12 Years ago, fri, october 19, 2012, 12:00:00

I would like the ability to load templates dynamically without explicitly specifying the template.



As an example:



<template name=foo>
</template>


where 'foo' is the template, I would like the ability to load it dynamically by calling some method:



Meteor.render(Meteor.loadTemplate('foo'));


Is this possible?


More From » meteor

 Answers
671

Meteor 0.9.x New API



Dan Dascalescu pointed out Meteor now has built-in dynamic templates! This is nice because you do not need to include the extra code as seen in previous versions.



{{> Template.dynamic template=template [data=data] }}


For Meteor 0.8.x Legacy



Dynamic Template Without Data: Boris Kotov's updated Blaze (0.8.0) answer is on the right track (taken from the latest docs), but it doesn't work as-is for me. I got the following to work:



{{> dynamicTemplate name=myDynName}}

<template name=dynamicTemplate>
{{#with chooseTemplate name}}
{{> template}}
{{/with}}
</template>

Template.dynamicTemplate.chooseTemplate = function (name) {
return { template: Template[name] };
};


I hope there is a simpler solution, but I needed to wrap the Template in a JSON as shown. Maybe this will help someone else to move forward.



Dynamic Template With Data: If you have and want data to be dynamic, be sure to make a helper method that can react. Be sure to do a Session.set() somewhere to see the effect.



// Inside myContainingTemplate
{{> dynamicTemplateWithData name=myDynName data=myDataHelper}}

<template name=dynamicTemplateWithData>
{{#with chooseTemplate name}}
{{#with ../data}}
{{> ..}}
{{/with}}
{{/with}}
</template>

Template.dynamicTemplateWithData.chooseTemplate = function (name) {
return Template[name];
};

Template.myContainingTemplate.helpers({
myDataHelper: function () {
Session.get('myReactiveKey');
}
});

[#82480] Wednesday, October 17, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
denver

Total Points: 232
Total Questions: 111
Total Answers: 103

Location: South Korea
Member since Sat, Oct 2, 2021
3 Years ago
;