Templates 获取流星模板的内容

Templates 获取流星模板的内容,templates,meteor,Templates,Meteor,我有以下流星模板: <template name="homeBoxTpl"> <div> Some content </div> </template> <template name="homeBoxTpl"> <div class="content-container"> Some content </div> <button id

我有以下流星模板:

<template name="homeBoxTpl">
    <div>
        Some content
    </div>
</template>
<template name="homeBoxTpl">
    <div class="content-container">
        Some content
    </div>
    <button id="btn" type="button">Click me</button>
</template>

一些内容

我有一个事件绑定,因此当单击页面上的按钮时,它应该会得到模板“homeBoxTpl”的html内容-如何实现这一点?

您可以使用jquery访问所需内容。例如,如果您有以下模板:

<template name="homeBoxTpl">
    <div>
        Some content
    </div>
</template>
<template name="homeBoxTpl">
    <div class="content-container">
        Some content
    </div>
    <button id="btn" type="button">Click me</button>
</template>
你需要的是一个,就像Chase说的,你可以使用jquery访问meteor模板的内容,但是meteor有自己的方式。为了获得html的副本,您可以在模板中的内容周围放置一个包装器,然后执行以下操作:

Template.homeBoxTpl.events({
  'click #someButton':function(e,t){
       var templateContents = t.$('.wrapperInTemplate').html();  
  }
})
这里我们使用wich返回这些元素的jQuery对象


查看更多信息,只需澄清一下,按钮在哪里?它在另一个模板中吗?我假设您只渲染一次homeBoxTpl

在这种情况下,按钮所在模板的事件处理程序将不会引用其他模板实例。没有全局查找,您可以在其中找到特定
模板的所有渲染实例

您必须为它设置一个唯一的标识符“id”,或者一些其他有区别的信息,比如类/属性,然后通过老式的JSDOM选择器/遍历找到它

document.getElementById
是最快的,但是如果该模板有多个实例,
t.firstNode
确实为DOM遍历提供了一个良好的起点

但是,使代码依赖于特定的DOM布局是一种不好的做法/耦合太多。是否有任何原因导致该模板HTML内容的基础数据在其他地方(如会话或集合)不可用?访问数据而不是HTML可能也更灵活