8

好的,所以我在自己的名为 myApp.html 的文件中找到了我的模板。我的模板代码如下

<template name="initialInsertion">
  <div class="greeting">Hello there, {{first}} {{last}}!</div>
</template>

现在我想在单击按钮时将此模板插入 DOM。我已经在 DOM 中呈现了我的按钮,并且我有一个与其相关的点击事件,如下所示

Template.chooseWhatToDo.events = {
  'click .zaButton':function(){
     Meteor.ui.render(function () {
       $("body").append(Template.initialInsertion({first: "Alyssa", last: "Hacker"}));
     })
  }
}

现在显然 $("body").append 部分是错误的,但返回 Template.initialInsertion... 不会将该模板插入 DOM。我试过放一个partia {{> initialInsertion}},但这只是错误,因为我还没有第一组和最后一组......任何线索?多谢你们

4

4 回答 4

14

在流星 1.x 中

'click .zaButton':function(){
   Blaze.renderWithData(Template.someTemplate, {my: "data"}, $("#parrent-node")[0])
 }

在流星 0.8.3

'click .zaButton':function(){
   var t = UI.renderWithData(Template.someTemplate, {my: "data"})
   UI.insert(t, $(".some-parrent-to-append"))
 }
于 2014-08-23T20:44:02.317 回答
6

第一个和最后一个最终会进入 Meteor.Collection 吗?

如果没有,我知道的最简单的方法是将数据放入会话中:

Template.chooseWhatToDo.events = {
    'click .zaButton' : function () {
         Session.set('first', 'Alyssa');
         Session.set('last', 'Hacker');
    }
}

然后你会定义:

Template.initialInsertion.first = function () {
  return Session.get('first');
}

Template.initialInsertion.last = function () {
  return Session.get('last');
}

Template.initialInsertion.has_name = function () {
  return Template.initialInsertion.first() && Template.initialInsertion.last();
}

最后,像这样调整您的 .html 模板:

<template name="initialInsertion">
    {{#if has_name}}
        <div class="greeting">Hello there, {{first}} {{last}}!</div>
    {{/if}}
</template>

这是与您的问题完全相反的解决方案,但它似乎是“流星方式”。(基本上,不用担心自己操作 DOM,只需包含会话、集合和模板系统。)顺便说一句,我还是 Meteor 的新手,所以如果这不是“Meteor 方式”,请告诉我:-)

于 2012-05-01T20:17:27.320 回答
3

我认为您可能想在附加语句中使用 Meteor.render 。另外,请注意,如果您将数据传递到模板中,则必须将 Template.initialInsertion 包装在匿名函数中,因为这是 Meteor.render 所期望的。我正在做类似的事情,似乎正在工作:

Template.chooseWhatToDo.events = {
  'click .zaButton':function(){
    $("body").append(Meteor.render(function() {
      return Template.initialInsertion({first: "Alyssa", last: "Hacker"})
    }));
  }
}

希望这可以帮助!

于 2012-09-30T01:51:13.717 回答
1

这里的许多答案都会遇到新的 Blaze 引擎的问题。这是一个在 Meteor 0.8.0 中使用 Blaze 的模式。

//HTML
<body>
  {{>mainTemplate}}
</body>

//JS Client Initially
var current = Template.initialTemplate;
var currentDep = new Deps.Dependency;

Template.mainTemplate = function()
{
  currentDep.depend();
  return current;
};

function setTemplate( newTemplate )
{
    current = newTemplate;
    currentDep.changed();
};

//Later
setTemplate( Template.someOtherTemplate );

本节Meteor 文档中的更多信息

于 2014-03-30T18:18:00.037 回答