如何在HTML中使用把手

时间:2019-04-05 05:25:17

标签: javascript handlebars.js

我已经在车把中创建了一个自定义中断功能,并试图在html中使用它。将html呈现到浏览器时,它没有显示预期的结果。如果标签放错了位置,请纠正我。

<html>
<head>
  <title>Hello World</title>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>

  <script id="handlebars-demo" type="text/x-handlebars-template">
     {{#break students}}
     {{name}} has passed in {{passingYear}}.<br>
  {{/break}}      
  </script>

</head>
<body>

{{name}} has passed in {{passingYear}}.<br>

<script>
Handlebars.registerHelper("break", function(data,options) {

  var context = {
  "students": [{
    "name": "mrinal",
    "passingYear": 2013
  }, {
    "name": "raman",
    "passingYear": 2016
  },    
    {
    "name": "John",
    "passingYear": 2018 
  }]
}

  var len = data.length;
  var returnData = "";

 // custom break function 
for (var i = 0; i < len; i++) {
    if(data[i].passingYear<2015){
      return  returnData = returnData + options.fn(data[i]);
      i=len+1;
    } else{
      return  returnData = returnData + options.fn(data[i]);
    }}
})
var template = $('handlebars-demo').html();
var templateScript = Handlebars.compile(template);

var html = templateScript(context);
$(document.body).append(html);
</script>


</body>
</html>

expected result: 
mrinal has passed in 2013.

请仔细阅读代码并分享是否需要更正。

1 个答案:

答案 0 :(得分:0)

很多错误:

  • 您已经混合了车把帮助器的声明(即使定义了附加到帮助器的函数也不是函数)与数据的编译和呈现。摆出您的上下文以及不需要在帮助程序中的内容。
  • 您没有声明jquery,但使用它($)必须包含jquery
  • 您调用jquery从模板中获取html,但选择器错误:如果要让ID跟随在尖锐字符之后,则必须在选择器前放置#字符。

工作版本如下:

var context = {
  "students": [
    {
      "name": "mrinal",
      "passingYear": 2013
    }, 
    {
      "name": "raman",
      "passingYear": 2016
    },    
    {
      "name": "John",
      "passingYear": 2018 
    }
  ]
} 

Handlebars.registerHelper("break", function(data,options) {
  var len = data.length;
  var returnData = "";
 // custom break function 
  for (var i = 0; i < len; i++) {
      if(data[i].passingYear<2015){
        return  returnData = returnData + options.fn(data[i]);
        i=len+1;
      } else {
        return  returnData = returnData + options.fn(data[i]);
      }
  }
});

var template = $('#handlebars-demo').html();
var templateScript = Handlebars.compile(template);
var html = templateScript(context);
$("#placeholder").append(html);
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>

  <script id="handlebars-demo" type="text/x-handlebars-template">
  {{#break students}}
     {{name}} has passed in {{passingYear}}.<br>
  {{/break}}      
  
  {{name}} has passed in {{passingYear}}.<br>
  </script>

<div id="placeholder"></div>

expected result: 
mrinal has passed in 2013.