Handlebars将一个字符串或Handlebars AST传递给Handlebars编译

use*_*218 14 html javascript handlebars.js

我知道它被问了很多次,我看了答案,不知道我哪里出错了.

我查看了Handlebarsjs上的文档,并按照教程进行操作,两次都得到同样的错误.

<!DOCTYPE html>
<html>
  <head>
     <script src="handlebars-v1.3.0.js"></script>
     <script src="jquery.min.js"></script>
     <script src="test.js"></script>
  </head>
  <body>
    <script id="header" type="text/x-handlebars-template">
      div {{ headerTitle }} div
      Today is {{weekDay}}
    </script>
  </body>   
</html>
Run Code Online (Sandbox Code Playgroud)

这是我的Javascript

var theData = {headerTitle:"name", weekDay:"monday"}
var theTemplateScript = $("#header").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(document.body).append(theTemplate(theData));
Run Code Online (Sandbox Code Playgroud)

我继续得到以下错误,我不确定为什么

Uncaught Error: You must pass a string or Handlebars AST to Handlebars.compile. 
You passed undefined 
Run Code Online (Sandbox Code Playgroud)

Rob*_*_vH 23

在将模板脚本加载到DOM之前,您正在运行Handlebars.compile().将test.js移到模板脚本下面,你应该很高兴.


小智 7

将脚本移动到页面底部也对我有用.

<!DOCTYPE html>
 <html>
   <head>

   </head>
     <body>
        <script id="header" type="text/x-handlebars-template">
            div {{ headerTitle }} div
            Today is {{weekDay}}
        </script>

        <script src="handlebars-v1.3.0.js"></script>
        <script src="jquery.min.js"></script>
        <script src="test.js"></script>

   </body>   
 </html>
Run Code Online (Sandbox Code Playgroud)