关于javascript:Handlebars将字符串或AST传递给Handlebars进行编译

Handlebars Pass a string or Handlebars AST to Handlebars compile

我知道它被问过很多次了,我已经看了答案,但不确定我要去哪里。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
  <head>
     <script src="handlebars-v1.3.0.js">
     <script src="jquery.min.js">
     <script src="test.js">
  </head>
  <body>
    <script id="header" type="text/x-handlebars-template">
      div {{ headerTitle }} div
      Today is {{weekDay}}
   
  </body>  
</html>

这是我的Javascript

1
2
3
4
var theData = {headerTitle:"name", weekDay:"monday"}
var theTemplateScript = $("#header").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(document.body).append(theTemplate(theData));

我不断收到以下错误,我不确定为什么

1
2
Uncaught Error: You must pass a string or Handlebars AST to Handlebars.compile.
You passed undefined


在将TemplateScript加载到DOM之前,您正在运行Handlebars.compile()。将您的test.js移到模板脚本下方,您应该会很好。


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
 <html>
   <head>

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

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

   </body>  
 </html>

就像其他人所说的那样,问题在于您正在运行Handlebars.compile(),然后将TemplateScript加载到DOM中。

将您的javascript调用放在$(document).ready()中,请确保首先加载所有html。

1
2
3
4
5
6
7
8
var theData = {headerTitle:"name", weekDay:"monday"}

$(document).ready(function(){
  var theData = {headerTitle:"name", weekDay:"monday"}
  var theTemplateScript = $("#header").html();
  var theTemplate = Handlebars.compile(theTemplateScript);
  $(document.body).append(theTemplate(theData));
});

就我而言,我试图为更深层次的步骤分配一些价值,因此,我遇到了错误。

在我的代码之前

app.use(function (req, res, next) {
res.locals.partials.weather = {}; = getWeatherData();
next();
});

问题是

res.locals.partials.weather

删除部分图层后,我的问题消失了。

最终的代码是

app.use(function (req, res, next) {
res.locals.weather = getWeatherData();
next();
});


就我而言,我遇到了相同的错误,但是问题是html页面中的模板脚本中有错字。我有"产品模板"应该是"产品模板":

1
2
    <script id="prouct-template" type="text/x-handlebars-template">
    ...

一旦我纠正了错字,错误就会消失并且页面可以正常加载。


JavaScript文件需要进行一些修改。我遇到过同样的问题。在我的代码中,我从Views调用了" handlebars"(以下是针对View的解释)。

在View的初始化函数(init)中包括以下内容:

theTemplate = Handlebars.compile(theTemplateScript);

在渲染中,编写其余代码:

var theTemplate = Handlebars.compile(theTemplateScript);
$(document.body).append(theTemplate(theData));

正确的方法是预编译处理程序,将其存储在文件中,然后将其分配给theTemplate