3

有谁知道如何在 HTML 页面中打印 .hbs/.handlebars 模板?我到处寻找,但我不知道如何将 .hbs 文件放在一个目录中,然后将它们打印到我的 index.html 中。抱歉这个问题,但我是车把的新用户。提前致谢!

4

2 回答 2

7

假设您有一个车把模板post.handlebars

<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>

使用车把预编译器来编译您的模板:

$ handlebars post.handlebars -f templates.js

在您的 html 文档中包含已编译的模板和车把运行时

<script src="/libs/handlebars.runtime.js"></script>
<script src="templates.js"></script>

现在编译后的模板可以作为Handlebars.templates. 接下来将数据传递给模板,生成一些 html 并将其附加到 DOM。

<script type="text/javascript">
   var template = Handlebars.templates.post;
   var context = {title: "My New Post", body: "This is my first post!"};
   var html    = template(context);
  
 $(document).append(html);
</script>

有关预编译的详细信息,请参阅http://handlebarsjs.com/precompilation.html。这里还有一个很棒的车把教程:http: //javascriptissexy.com/handlebars-js-tutorial-learn-everything-about-handlebars-js-javascript-templating/

于 2013-04-26T12:19:58.463 回答
1

将您的 hbs 文件保存为片段文件。说 myTemplate.jspf

将其包含在您的 HTML/JSP 文件中,如下所示

<script type="text/x-handlebars-template"> 
   <%@ include file="myTemplate.jspf" %>
</script>
于 2014-11-04T12:27:48.297 回答