背景:之前写前后端不分离的项目,都是通过ThinkTemplate(thinkphp)和Thymeleaf、FreeMarker(Java)去实现的,但是有些数据需要动态去体现使用过ajax去手动操作dom通常有点麻烦,偶然间知道这个js模板照旧蛮感兴趣,功能强盛。
文章目录
一、Handlebars.js是什么?
二、使用步调(each-基本循环使用方法)
三、进阶
总结
前言
小弟之前愚蠢的想法就是ajax请求的话都是一个一个去添加,每一块内容先拼接好一整块,然后再循环输出。(这里指ajax请求的环境下,其他环境下不分离模板直接for很快的)
直到今天,遇到了handlebars.js
handlebars.js可以在提前设置好的模板内渲染出内容,功能强盛下面演示
提示:以下是本篇文章正文内容,下面案例可供参考
一、Handlebars.js是什么?
Handlebars.js是一个Javascript客户端的模板引擎(它也能用于服务器端)。它是一个Javascript库,就像你在页面中包含其他.js文件一样。有了它,在你的HTML页面内添加模板,模板会被你通过Handlebars.js函数传递的数据中的值剖析大概插值。
二、使用步调(each-基本循环使用方法)
1.设置模板
代码如下:
html:
- <body>
- <script id="template" type="text/x-handlebars-template">
- <ul>
- {{#each items}}
- <li>{{this.name}} - {{this.value}}</li>
- {{/each}}
- </ul>
- </script>
- <div id="result"></div>
- <a href="javascript:;" onclick="ceshi()">测试</a>
- <a href="javascript:;" onclick="xuanran()">渲染</a>
- </body>
复制代码 template就是我们设置好的模板,相当于你设置好了一个商品展示卡(我上面的图)
2.Ajax获取数据
代码如下:
Javascript:
- <script>
- function ceshi(){
- $.ajax({
- type: "GET",
- url: "",
- success: function(e) {
- console.log(e)
- },
- error: function() {
- console.log('失败')
- }
- })
- };
- function xuanran(){
- $.ajax({
- url: '',
- method: 'GET',
- success: function(data) {
- var source = $('#template').html();
- var template = Handlebars.compile(source);
- var html = template({ items: data.data });
- console.log(html);
- $('#result').html(html);
- }
- });
- };
- </script>
复制代码 这里是利用Ajax去请求后端获取数据。
这里可以看出,数据是从这边传进去的:
- template({ items: data.data });
复制代码
3.后端提供数据
- public function test()
- {
- $a = [
- ['name' => '名字','value' => '小明'],
- ['name' => '年龄','value' => '18'],
- ['name' => '性别','value' => '男'],
- ['name' => '身高','value' => '181'],
- ['name' => '体重','value' => '70kg'],
- ];
- if(false === $this->request->isAjax())
- {
- return view();
- }
- return api($a,200,'请求成功');
-
- }
复制代码 这里是测试数据故意弄成如许子
这种数据格式也是经常见吧,不像通例的很好认的那种
结果
点击获取数据后就会渲染。
分析
你得到数据之后,他是如许的
- //这个js
- var html = template({ items: data.data });
- //说明你已经拿到这样的数据了
- "data": [
- {
- "name": "名字",
- "value": "小明"
- },
- {
- "name": "年龄",
- "value": "18"
- },
- {
- "name": "性别",
- "value": "男"
- },
- {
- "name": "身高",
- "value": "181"
- },
- {
- "name": "体重",
- "value": "70kg"
- }
- ]
- //然后这边#each表示进入
- {{#each items}}
- //说明到达每一块
- {
- "name": "名字",
- "value": "小明"
- }
- //这里你就只能用
- {{this.name}} - {{this.value}}
- //这种模板还是很可以
复制代码
三、进阶
如许我们就可以做更复杂的操作了
each-基本循环使用方法
前端:
- <body>
- <h1>each-基本循环使用方法</h1>
- <!--基础html框架-->
- <table>
- <thead>
- <tr>
- <th>姓名</th>
- <th>性别</th>
- <th>年龄</th>
- </tr>
- </thead>
- <tbody id="tableList">
- </tbody>
- </table>
- <!--id可以用来唯一确定一个模版,type是模版固定的写法-->
- <script id="table-template" type="text/x-handlebars-template">
- {{#each student}}
- <tr>
- <td>{{name}}</td>
- <td>{{sex}}</td>
- <td>{{age}}</td>
- </tr>
- {{/each}}
- </script>
- </body>
复制代码- <!--进行数据处理、html构造-->
- <script type="text/javascript">
- $(document).ready(function () {
- $.ajax({
- url:'student',
- method:'GET',
- success:function(data){
- var myTemplate = Handlebars.compile($("#table-template").html());
- //将json对象用刚刚注册的Handlebars模版封装,得到最终的html,插入到基础table中。
- $('#tableList').html(myTemplate(data.data));
- }
- });
- });
- </script>
复制代码 后端:
- public function test1()
- {
- if(false === $this->request->isAjax())
- {
- return view();
- }
- }
- public function student()
- {
- $student = [
- [
- 'name' => "张三",
- 'sex' => "男",
- 'age' => 28
- ],
- [
- 'name' => "李四",
- 'sex' => "女",
- 'age' => 30
- ],
- [
- 'name' => "妞妞",
- 'sex' => "女",
- 'age' => 32
- ]
- ];
- return api(['student'=>$student],200,'请求成功');
- }
复制代码
应该很好分析这个是干嘛的
with-进入到某个属性(进入到某个上下文环境)
分析:
首先来构造一个复杂的json(工作中经常遇到的,给前端小姐姐上点压力)
先给各人看看前端的页面加载出来是没有数据的
等到数据出来时,他才开始渲染出来:(其实这一直是我想要的,用vue大概其他也能达到这种结果,但是照旧喜欢有些杂糅在一起的)
代码如下:
前端:
- <body>
- <h1>with-进入到某个属性(进入到某个上下文环境)</h1>
- <!--基础html框架-->
- <table>
- <thead>
- <tr>
- <th>姓名</th>
- <th>性别</th>
- <th>年龄</th>
- <th>兴趣爱好</th>
- </tr>
- </thead>
- <tbody id="tableList">
- </tbody>
- </table>
- <!--Handlebars.js模版放在script标签中,保留了html原有层次结构,模版中要写一些操作语句-->
- <!--id可以用来唯一确定一个模版,type是模版固定的写法-->
- <script id="table-template" type="text/x-handlebars-template">
- {{#each this}}
- <tr>
- <td>{{name}}</td>
- <td>{{sex}}</td>
- <td>{{age}}</td>
- <td>
- {{#with favorite}}
- {{#each this}}
- <p>{{name}}</p>
- {{/each}}
- {{/with}}
- </td>
- </tr>
- {{/each}}
- </script>
- </body>
复制代码- <!--进行数据处理、html构造-->
- <script type="text/javascript">
- $(document).ready(function() {
- $.ajax({
- url:'test2api',
- method:'GET',
- success:function(data){
- //$("#table-template").html()是jquery的语法。。。
- var myTemplate = Handlebars.compile($("#table-template").html());
- //将json对象用刚刚注册的Handlebars模版封装,得到最终的html,插入到基础table中。
- $('#tableList').html(myTemplate(data.data.student));
- }
- });
- });
- </script>
复制代码
后端:
- public function test2()
- {
- if(false === $this->request->isAjax())
- {
- return view();
- }
- }
- public function test2api()
- {
- $student = [
- [
- 'name' => "张三丰",
- 'sex' => "男",
- 'age' => 28,
- 'favorite' =>[
- ['name' => "唱歌"],
- ['name' => "篮球"]
- ]
- ],
- [
- 'name' => "李妮妮",
- 'sex' => "女",
- 'age' => 30,
- 'favorite' =>[
- ['name' => "上网"],
- ['name' => "足球"]
- ]
- ],
- [
- 'name' => "王妞妞",
- 'sex' => "女",
- 'age' => 18,
- 'favorite' =>[
- ['name' => "电影"],
- ['name' => "旅游"]
- ]
- ]
- ];
- return api(['student'=>$student],200,'请求成功');
- }
复制代码
这个老哥写的好,可以参考他的,我也是参考他的:JavaScript页面模版引擎handlebars.js学习及使用_handlebars.js for-CSDN博客
对了我这tp8写的返回json的函数是这个:
- function api($data, $code = 200, $msg = 'Success')
- {
- $result = [
- 'code' => $code,
- 'message' => $msg,
- 'data' => $data,
- ];
- return json($result);
- }
复制代码 放在公共函数那里
总结
Ajax渲染页面的很早就想用找不到方便的,奈何本身就懒得写dom(我很菜),找到这个可以做很多事。
有的时候咱页面又不想被扒下来,就可以用这种方式
1.在Ajax请求的时候加个加个参数:域名照旧其他加密起来,传已往参数(域名)不对,就得不到数据了,跨域也给它开上。
- var domain = document.domain;
- $.ajax({
- url: '/xxxxx?domain='+domain,
- method: 'GET',
- success: function(data) {
- var source = $('#template').html();
- var template = Handlebars.compile(source);
- var html = template({ items: data.data });
- console.log(html);
- $('#result').html(html);
- }
- });
复制代码
2.把F12禁用掉,不要让他看到咱返回的数据结构。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |