【问题标题】:Compiling and rendering handlebars template with vanilla JS使用 vanilla JS 编译和渲染车把模板
【发布时间】:2016-10-22 08:04:19
【问题描述】:

我正在编写一个使用 handlebars.js 的应用程序,但 The example code on their website 使用 JQuery 以及许多其他在线资源。但是,我想使用 vanilla js 简单地编译和渲染车把模板。

这是 HTML 模板

<script id="entry-template" type="text/x-handlebars-template">
  <div class="entry">
    <h1>{{title}}</h1>
    <div class="body">
     {{body}}
    </div>
  </div>
</script>

我为编译所拥有的 JS 在下面,正如在此处对类似问题的回答中所建议的那样 Does Handlebars require jQuery

var source = document.getElementById('entry-template').innerHTML;
var template = Handlebars.compile(source);

假设我的 JSON 存储在名为 myData 的变量中。

当涉及到使用 JQuery 渲染模板时,您可以简单地做

$('#data-section').append(template(myData));

但我想使用 vanilla JS,所以我这样做:

var compiledHTML = template(myData);    
var dataContainer = document.getElementById('data-section');
dataContainer.appendChild(compiledHTML);

但我得到了错误

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

如何让它工作?

【问题讨论】:

    标签: javascript templates handlebars.js


    【解决方案1】:

    您可以使用跨浏览器友好的Element.insertAdjacentHTML 方法。
    请参阅此处的文档: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

    如何将编译后的模板插入 DOM 有四个选项:

    1. beforebegin(在开始标签之前或作为前一个兄弟)
    2. afterbegin(第一个孩子)
    3. beforeend(最后一个孩子)
    4. afterend(在结束标记或下一个兄弟之后)

    在我的例子中,我将一个模板附加到 body 标签的末尾,所以它看起来像这样 document.getElementsByTagName('body')[0].insertAdjacentHTML("beforeend", myHbsTemplate(VM));

    【讨论】:

    【解决方案2】:

    调用已编译模板的输出是字符串,而不是 DOM 树。您可能想改用innerHTML

    dataContainer.innerHTML = compiledHTML;
    

    【讨论】:

    【解决方案3】:

    问题似乎在于变量 compiledHTML 是一个字符串。我采用的解决方案是使用 DOMparser,它允许我将字符串转换为 DOM 节点,然后我可以将其传递给 appendChild。

    我使用的代码是这样的

    var parser = new DOMParser();
    var convertedHtml = parser.parseFromString(compiledHTML, 'text/xml');
    dataContainer.appendChild(convertedHtml.documentElement);
    

    我必须使用 documentElement 因为解析产生的 HTML 会产生 HierarchyRequestError 错误。

    【讨论】:

      猜你喜欢
      • 2018-11-13
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 2019-07-27
      • 2013-05-14
      相关资源
      最近更新 更多