如何获取并打印.hbs或.handlebars模板?
问题描述:
有谁知道如何在HTML页面中打印.hbs/.handlebars模板?我到处寻找,但我不知道如何将.hbs文件放在一个目录中,然后在我的index.html中打印它们。抱歉的问题,但我是一个新的车把手用户。提前致谢!如何获取并打印.hbs或.handlebars模板?
答
比方说,你有一个把手模板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/
答
将你的hbs文件保存为片段文件。说myTemplate.jspf
在你的HTML/JSP文件中包含该如下
<script type="text/x-handlebars-template">
<%@ include file="myTemplate.jspf" %>
</script>