在Meteor.js中动态加载模板 [英] Dynamically loading templates in Meteor.js
问题描述
我希望能够动态加载模板而无需明确指定模板。
I would like the ability to load templates dynamically without explicitly specifying the template.
例如:
<template name="foo">
</template>
其中'foo'是模板,我希望能够通过调用某种方法动态加载它:
where 'foo' is the template, I would like the ability to load it dynamically by calling some method:
Meteor.render(Meteor.loadTemplate('foo'));
这可能吗?
推荐答案
流星0.9.x新API
Dan Dascalescu指出Meteor现在有内置的动态模板!这很好,因为您不需要包含以前版本中的额外代码。
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] }}
对于Meteor 0.8.x遗产
动态模板没有数据:Boris Kotov更新后的Blaze(0.8.0)答案是在正确的轨道上(取自最新的文档),但它对我来说不起作用。我得到以下工作:
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] };
};
我希望有一个更简单的解决方案,但我需要将模板包装在JSON中,如图所示。也许这会帮助其他人继续前进。
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.
动态模板使用数据:如果您有并希望数据是动态的,请务必制作一个可以做出反应的辅助方法。一定要在某处查看Session.set()以查看效果。
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');
}
});
这篇关于在Meteor.js中动态加载模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!