在 Meteor.js 中动态加载模板 [英] Dynamically loading templates in Meteor.js

查看:12
本文介绍了在 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'));

这可能吗?

推荐答案

Meteor 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 Legacy

动态模板没有数据: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.

Dynamic Template With 数据:如果您拥有并希望数据是动态的,请务必制作一个可以做出反应的辅助方法.一定要在某处做一个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆