刚接触 Handlebars 问下如何将 Ajax 的数据与外部 Handlebars 模板绑定,然后再插入到页面中~
代言
代言 2016-11-07 14:37:34
0
1
1570

我有一共有三个文件:

//- 模板文件 menu.hbs
<script id="template" type="text/x-handlebars-template">
{{#each this}}
<h3>{{title}}</h3>
<div>{{content}}</div>
{{/each}}
</script>
//- JSON数据
menu.json
[{
"title": "统计报表",
"content": "统计报表的内容~"
},{
"title": "活动统计",
"content": "活动统计的内容~"
},{
"title": "店铺统计",
"content": "店铺统计的内容~"
}]
//- 页面入口文件
index.html
<div class="wrapper" id="wrapper"></div>

我自己的思路是这样子的,我先 ajax 请求加载进来 json 数据,成功之后,再 ajax 请求 Handlebars 模板,再用前的 json 数据与 模板进行绑定,最后插入到页面中~

感觉很别扭,不知道是否正确~

代言
代言

Antworte allen(1)
季伟

模板文件既可以放到js里面,也可以放到html文件里面或者单独的文件。


js里面就是字符串:

'{{#each this}}' + ' 

{{title}}

' + ' 
{{content}}
' + '{{/each}}'

html里面就是你上面写的那种:


单独文件就要异步请求: 可以使用上面那个朋友的 $.when方法,或者现在es6的promise。


Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!