[英]How can I append soy template return values as DOM nodes to the document body?
我目前正在通過以下方式將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')
,但這將涉及瀏覽goog.dom.$('idOfMyHeader')
操作,因為在顯示標題之后,會將新的DOM節點附加到標題中。
是否有將大豆模板(例如標頭)轉換為DOM節點的便捷方法?
可以使用Soy JavaScript庫函數soy.renderAsFragment
將閉包模板呈現為DOM片段。
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
屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.