【问题标题】:Pass data to a dynamic template将数据传递给动态模板
【发布时间】:2014-05-20 15:15:06
【问题描述】:

随着流星更新到 0.8,我的旧代码停止工作。

Handlebars.registerHelper('getTemplate', function(id, context) {
    return Template[id](context);
}); 

<template name="main">
    ....
    {{{getTemplate templateName context}}}
    ....
</template>

//somewhere in other template 
Template.main.context = {name:value};

通过这种方式,我能够使用自定义数据呈现自定义模板。现在我找不到将context 传递给动态模板的方法。对于 blaze,templateNamecontext 都是未定义的。有什么建议吗?

【问题讨论】:

标签: meteor meteor-blaze


【解决方案1】:

流星 >= 0.8.2

您可以使用UI.dynamic 帮助器渲染具有动态指定上下文的模板。更多详情,请查看this issue

流星

这两个问题都在流星维基的this page 上得到解决。

  1. Handlebars.registerHelper 现在是 UI.registerHelper,如 here 所示。

  2. 显示如何动态呈现模板的示例here


更新

实际上,鉴于要求,解决方案对我来说似乎不是很明显。如果您愿意使用会话变量来设置模板名称和上下文,并且您的主模板中只有一个动态模板。你可以这样做:

<body>
  {{> main}}
</body>

<template name="main">
  {{> getTemplate context}}
</template>

<template name="dogs">
  <p>There are {{animals}} dogs!</p>
</template>

<template name="cats">
  <p>There are {{animals}} cats!</p>
</template>
Session.setDefault('templateName', 'dogs');
Session.setDefault('templateContext', {animals: 10});

Template.main.getTemplate = function() {
  return Template[Session.get('templateName')];
};

Template.main.context = function() {
  return Session.get('templateContext');
};

【讨论】:

  • 当然,在提问之前我已经阅读过了。它没有帮助。
  • 是的,这比我想象的要难。我用一个使用会话变量的示例更新了答案。这可能不是您想要的,因为它不是很可重用。
  • @Serge 在meteor 0.8.2 中有一个名为UI.dynamic 的新助手,它可能有助于解决您的问题。我用详细信息的链接更新了答案。
【解决方案2】:

这是在流星核心列表中提出的,@dgreensp,正在开发 Blaze 的 MDG 核心开发人员,打开了Ticket #2007 - How to render a template to HTML with data,所以他们肯定知道这一点,我希望在 0.8.0 之后很快就会有一个修复。

他还提供了以下解决方法:

var toHTMLWithData = function (kind, data) {
  return UI.toHTML(kind.extend({data: function () { return data; }}));
};

github 票有进一步的讨论和替代代码 sn-ps,您可能会觉得有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    相关资源
    最近更新 更多