如何使用Handlebarsjs使用预编译的模板

时间:2019-04-30 16:29:59

标签: asp.net-core handlebars.js

我正在使用handlebarsjs在ASP.NET Core应用程序中构建模板。

我想预编译模板并将其值存储到`div中。然后在按钮上单击以检索预编译的模板并传递上下文信息

(顺便说一句,在生产中,我们会将预编译的模板存储在div中不在的sql数据库中)

JSFiddle

HTML

<!-- store pre-complied source -->
<div id="preCompileSrc"></div>
<p/>

<!-- click button to evaluate -->
<button type="button" id="btn">Click Me</button>

<!-- rendered html -->
<div id="myhtml"></div>

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

JavaScript

$(function () {

    // store pre-compiled into div
    var source = $("#entry-template").html();
    var str = Handlebars.precompile(source);
    $("#preCompileSrc").text(str);


  $("#btn").click(function () {
        evaluatePreCompile();
    }); 


  function evaluatePreCompile() {
    var data = getData();
    var str = $("#preCompileSrc").text();
    var template = Handlebars.template(str); // throws error here
    var html = template(data);
    $("#myhtml").html(html);
  }

  function getData() {
    return {
      title: "My New Post",
      body: "This is my first post!",
      people: [
        { firstName: "Yehuda", lastName: "Katz" },
        { firstName: "Carl", lastName: "Lerche" },
        { firstName: "Alan", lastName: "Johnson" }
      ]

    };
  }
});

当前,当我单击按钮时,出现以下错误

enter image description here

0 个答案:

没有答案