7

我在 Meteor 中有三个简单的模板,在服务器上有一个集合,它们的名称可以任意组合。我希望能够根据集合中的名称动态呈现这些模板。

目前我正在尝试通过使用客户端订阅集合并通过模板函数访问名称来完成此操作。不幸的是,如果我尝试在名称上运行“>”,Meteor 会尝试呈现变量名称而不是其值所指向的模板。

因此,不是在template1template2template3中呈现 html,而是输出仅仅是它们在页面上的名称:“template1 template2 template3”。

这是我一直在使用的代码,我希望有一种方法可以解决我的问题,而无需手动运行 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>
4

3 回答 3

4

你可以做一个render助手:

 Handlebars.registerHelper('render', function(name, options) {
   if (Template[name])
     return new Handlebars.SafeString(Template[name]());
 });

并与它一起使用

{{render templateName}}
于 2012-11-29T06:27:48.333 回答
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
于 2012-11-24T03:44:37.310 回答
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}}
于 2014-10-28T22:31:55.353 回答