如何从模板名称的集合中渲染Meteor模板?

7
我在Meteor中有三个简单的模板和一个集合(Collection), 集合中包含它们任意组合的名称。我想根据集合中的名称动态地渲染这些模板。
目前,我的解决方法是让客户端订阅该集合,并通过模板函数访问名称。但是,如果我尝试对名称运行“>”,Meteor会尝试呈现变量名称,而不是指向其值的模板。
因此,输出仅是页面上的它们的名称: "template1 template2 template3",而不是呈现template1template2template3的HTML。
以下是我一直在使用的代码,希望能找到一种解决问题的方法,而无需手动运行Meteor.render。
服务器js:
TemplatesToRender = new Meteor.Collection("templatesToRender");

TemplatesToRender.insert({templateName: "template3"});
TemplatesToRender.insert({templateName: "template2"});

客户端 HTML:

<body>
    {{#each templatesToRender}}
        {{> templateName}}           // meteor trying to render a template
                                     // called "templateName" instead of the 
                                     // variable inside templateName.
    {{/each}}
</body>

<template name="template1">
    <span>Template 1</span>
</template>

<template name="template2">
    <span>Template 2</span>
</template>

<template name="template3">
    <span>Template 3</span>
</template>
3个回答

4
你可以创建一个名为 render 的辅助函数:
 Handlebars.registerHelper('render', function(name, options) {
   if (Template[name])
     return new Handlebars.SafeString(Template[name]());
 });

并使用它与

{{render templateName}}

这里的问题是内存管理,因为你调用了Template[name]()函数,他一遍又一遍地重新生成模板。这种方法很好,但是在替换时没有正确地删除模板。我测试过了,当你插入和删除几千个条目后,会有50MB的内存堆积! - Fabian Vogelsteller

0
你可能想尝试这个
在你的HTML中
<body>

    {{> templateToRender}}

</body>

<template name="templateToRender">

    {{! use below to detect which template to render}}

    {{#if templateName "template1"}}
        {{> template1}}
    {{/if}}

    {{#if templateName "template2"}}
        {{> template3}}
    {{/if}}

    {{#if templateName "template3"}}
        {{> template3}}
    {{/if}}

</template

<template name="template1">

    <p>this is template1</p>

</template>

<template name="template2">

    <p>this is template2</p>

</template>

<template name="template3">

    <p>this is template3</p>

</template>

在你的脚本中

Template.templateToRender.templateName = (which) ->
    # if user have a field like templateName you can do things like
    tmplName = Meteor.user().templateName
    # Session.equals will cause a template render if condition is true.
    Session.equals which, tmplName

0
Meteor 1.0刚刚在今天发布,我只是想将其更新到2014年 :)

https://docs.meteor.com/#/full/template_dynamic

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

示例用法:

{{#each kitten}}
   {{> Template.dynamic template=kitten_type data=this }}
{{/each}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接