在没有AJAX的情况下将手柄模板抽象为外部文件

abstracting handlebars templates into external files w/o AJAX

本文关键字:抽象 文件 外部 AJAX 情况下      更新时间:2023-09-26

有什么方法可以更简单地加载手把模板吗?这似乎是一件容易的事情。如果我有以下index.html:代码

<body>
  <h1>From the index.html</h1>
  <div id="hbs"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
  <script id="test" type="text/x-handlebars-template">
      <h2>This is from HBS</h2>
      <p>
        hbs generated this p tag!
      </p>
    </script>
    <script src="js/script.js"></script>
</body>

以下是在js/script.js:中编译模板的脚本代码

var template = Handlebars.compile(document.querySelector("#test").innerHTML)
document.querySelector("#hbs").innerHTML = template({})

这很好,但当我打开index.html时,我可以看到通过模板生成的头和p标记。必须有一种简单的方法将这个模板抽象到一个单独的文件中!

您可以将模板放在hbs文件中:

template.hbs:

<script type="text/x-handlebars-template">
      <h2>This is from HBS</h2>
      <p>
        hbs generated this p tag!
      </p>
</script>

然后使用ajax获取文件,而不是使用querySelector获取html

$document.ready(function(){
   $.get( '/url/template.hbs', function( source ) {
      var template = Handlebars.compile(source);
      document.querySelector("#hbs").innerHTML = template({});
   }
});