将数据传递到动态模板

时间:2014-04-08 05:34:55

标签: meteor meteor-blaze

随着流星更新达到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传递给动态模板的方法。使用大火时,templateNamecontext都未定义。有什么建议?

2 个答案:

答案 0 :(得分:2)

Meteor&gt; = 0.8.2

您可以使用UI.dynamic帮助器渲染模板,其中包含动态指定的上下文。有关详细信息,请查看this issue

流星&lt; 0.8.2

这两个问题都在流星维基上this page处理。

  1. Handlebars.registerHelper现在是UI.registerHelper here

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


  3. 更新

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

    <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');
    };
    

答案 1 :(得分:1)

这是在流星核心列表上提出的,@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票证有进一步的讨论和备用代码片段,您可能会发现它们很有用。