如何将大豆模板返回值作为DOM节点附加到文档正文?

时间:2012-07-22 22:20:52

标签: google-closure-templates

我目前正在通过

将Google Closure Soy模板添加到我的HTML文档正文中
var header = app.ui.templates.home.header();
document.body.innerHTML =
  header + app.ui.templates.home.bottom({
      "widgets": widgets,
  });

但是,我不相信这是最佳的,因为大豆模板构造函数不会返回DOM节点。因此,我不能说致电goog.dom.appendChild(header, someNewElementICreated);

是否有方便的方法将大豆模板(比如header)转换为DOM节点?我可以调用goog.dom.$('idOfMyHeader'),但这将涉及浏览器重排操作,因为在标题已经显示之后,新的DOM节点被附加到标题。

1 个答案:

答案 0 :(得分:4)

  

有没有方便的方法将大豆模板(比如标题)转换为DOM节点?

Closure模板可以使用Soy呈现为DOM片段 JavaScript库函数soy.renderAsFragment

<强> app.js

goog.require('app.ui.templates');
goog.require('soy');

var fragment = soy.renderAsFragment(app.ui.templates.myTemplate, null /*data*/);
goog.dom.appendChild(goog.dom.getElementsByTagNameAndClass('body')[0],
    /** @type {Node} */ (fragment));

<强> templates.soy

{namespace app.ui.templates}

{template .myTemplate}
  <div>
    ...
  </div>
{/template}

由于此情况下呈现的模板是元素节点,因此可以将其转换为 一个Node并附加到DOM。但是,使用div更为常见 元素作为占位符并设置innerHTML属性。