template7framework7的内置模板引擎,在此之前使用过jquery-tmpl,不过刚刚打开github看了下,已经停止更新,并且将要被JsRender所替代。妹的,JsRender又是什么鬼啊?扯远了,之前听过别人关于jquery-tmpl模板引擎的技术分享,它的源码加上一堆注释才100多行。在此之前模板给我的概念是jsp那种,要与java后端一起配合使用的,后端用数据模型把值传到前台,前台再通过${}获取值。如果需要进行一些条件判断,则使用jstl。如果前台要异步局部刷新页面,则用ajax来实现,返回的数据以拼字符串的方式把DOM嵌入到原来的页面,但是拼字符串这种方式实在坑爹,不仅写来痛苦,维护起来也痛苦。后来就使用js动态添加HTML,然后再用js把数据填充进去。写法有以下两种:

  <script type="text/html" id="theTemplate">
<div class="dialog">
<div class="title">
<img src="close.gif" alt="点击可以关闭" />亲爱的提示条
</div>
<div class="content">
<img src="delete.jpg" alt="" /><span>您真的要GG吗?</span>
</div>
<div class="bottom">
<input id="Button2" type="button" value="确定" class="btn"/>&nbsp;&nbsp;
<input id="Button3" type="button" value="取消" class="btn"/>
</div>
</div>
</script> var template = document.getElementById("theTemplate").innerHTML ;

或:

<textarea id="theTemplate" style="display:none">
<div class="dialog">
<div class="title">
<img src="close.gif" alt="点击可以关闭" />亲爱的提示条
</div>
<div class="content">
<img src="delete.jpg" alt="" /><span>您真的要GG吗?</span>
</div>
<div class="bottom">
<input id="Button2" type="button" value="确定" class="btn"/>&nbsp;&nbsp;
<input id="Button3" type="button" value="取消" class="btn"/>
</div>
</div>
</textarea> var template = document.getElementById("theTemplate").value ;

这种写法优点是:

  1. 比拼字符串优雅很多

  2. 浏览器不会读取到就渲染,所以里面的img的src也不会自动获取

缺点:

  1. script标签里面不能直接写变量,又需要频繁的操作修改DOM。

可能是基于以上的缺点,引入了jquery-tmpl模板引擎,但我觉得前端模板的真正意义在于前后端分离,即无法通过controller把数据发送到view,只能以接口请求的形式得到数据,但是HTML本身又没有jstl或freemarker那样获取变量或者进行if判断、each循环的功能,所以,需要有一种工具来进行功能的替代,这时前端模板引擎纷纷出现,五花八门,像我们项目中有用到的underscore.js内置的模板引擎,但是那个功能比较单一,毕竟模板引擎只是他的一部分,功能够用就好。
而我们今天要说的template7,则是一个功能更为强大,更为全面的模板引擎,官方说它执行速度也很快,但是到底快不快,比哪些快,我没去研究,有兴趣的可以自己拿几种模板引擎对比下。

Template7还嵌入了handlebars的表达式{{#}}


<div class="list-block">
<ul>
{{#each items}}
<li class="item-content">
<div class="item-inner">
<div class="item-title">{{title}}</div>
</div>
</li>
{{/each}}
</ul>
</div>

其实个人不喜欢一个模板搞几种表达式,不过猜测作者应该是考虑到在多种情况下都可以使用,即{{}}可能在当前的上下文中有了其他的用法或者含义,如果我模板也请也使用这个就会产生冲突,至于能有什么用法,不要问我,我不知道,但我知道jquery-tmpl模板中有两种取变量值的写法,${}{{=}}${}的写法是和freemarker、jsp等模板的取值方法是一样的,所以会产生混淆,所以一般用{{=}}

模板中我们经常能见到的方法,这里就简单的一笔带过,相信看官网的介绍会更加明了。我们就主要说一下不常用的或者其他模板引擎里没有的一些功能。

Template7有以下表达式语法:

Variables

  • {{title}} - plain variable. Outputs "title" variable in current context

  • {{../title}} - plain variable. Outputs "title" variable in parent context

  • {{../../title}} - plain variable. Outputs "title" variable in parent context of parent context

  • {{this}} - plain variable. Outputs variable equals to current context

  • {{person.name}} - plain variable. Outputs variable equals to "name" property of "person" variable in current context

  • {{../person.name}} - plain variable. The same but for parent context

  • {{@index}} - access to additional data variable. Such data variables could be used in helpers

Block expressions

  • {{#each}} - begin of block expression

  • {{else}} - begin of block inverse expression (where supported)

  • {{/each}} - end of block expression

  • {{#each reverse="true"}} - begin of block expression with passed reverse:true hash arguments

Helpers
Helpers could be plain expressions and block expressions:

  • {{join myArray delimiter=", "}} - execute "join" helper and pass there "myArray" variable of current context and delimiter:', 'hash argument

以上比较少见的是{{../title}},{{this}},{{person.name}}{{@index}}这几种写法,那我们就举个栗子(非糖炒)说一下:

<script id="tmplOne" type="text/template7">
<p>Hello, my name is {{firstName}} {{lastName}}</p>
<ul>
{{#each arr}}
<li>{{sex}}======={{birthday}}======={{../firstName}}</li>
{{/each}}
</ul>
<p>----------------</p>
<ul>
{{#each arr reverse="true"}}
<li>{{sex}}======={{birthday}}</li>
{{/each}}
</ul>
</script> var context = {
firstName: 'John',
lastName: 'Doe',
arr: [
{
sex: 'boy',
birthday:'1991-1-1'
},
{
sex: 'girl',
birthday:'1991-2-2'
}
]
}; 输出如下:
Hello, my name is John Doe
boy=======1991-1-1=======John
girl=======1991-2-2=======John
----------------
girl=======1991-2-2
boy=======1991-1-1

到这里想必大家都已经看明白了吧,如果写成下面这样,

{{#each arr}}
<li>{{sex}}======={{birthday}}======={{firstName}}</li>
{{/each}}

{{firstName}}是无法取到值得,因为当前一级是arr里面,往上一级才能或取到值。

第二个:

<script id="tmplOne" type="text/template7">
<p>Here are the list of people i know:</p>
<ul>
{{#each people}}
<li>{{@index}}======== {{this.test}} ********{{this}}</li>
{{/each}}
</ul>
<p>{{person.name}}</p>
</script> var context = {
people: ['John Doe', {test:'test'}],
person: {
name: '虚空假面'
}
};
//输出结果:
Here are the list of people i know:
0======== ********John Doe
1======== test ********[object Object]
虚空假面

下面说一说内置的一些辅助方法:

{{join myArray delimiter=", "}}

这个也是很少见到,有什么用,怎么用?
官方是这么说的:This plain helper will join Array items to single string with passed delimiter

<p>Genres: {{join genres delimiter=", "}}</p>

{
genres: ['comedy', 'drama']
} 输出:
<p>Genres: comedy, drama</p>

这个方法有木有很像js中的join()方法,

<script type="text/javascript">
var arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
document.write(arr.join())
</script> 输出:
George,John,Thomas

其实两者的作用也是一样的,都是把数组对象转成字符串,并用指定符号隔开。

{{#each}}...{{else}}...{{/each}}

之前用过{{#if}}...{{else}}...{{/each}},但是见到{{#each}}...{{else}}...{{/each}}感觉一脸懵逼
看栗子吧:

<p>Car properties:</p>
<ul>
{{#each props}}
<li>{{@key}}: {{this}}</li>
{{else}}
<li>No properties</li>
{{/each}}
</ul>
<p>obj:</p>
<ul>
{{#each obj}}
<li>{{@key}}: {{this}}</li>
{{else}}
<li>No properties</li>
{{/each}}
</ul>
<p>exp:</p>
<ul>
{{#each exp}}
<li>{{@key}}: {{this}}</li>
{{else}}
<li>No properties</li>
{{/each}}
</ul>
var context = {
props: {
power: '150 hp',
speed: '200 km/h',
},
obj: {},
exp:false
}; 输出:
Car properties:
power: 150 hp
speed: 200 km/h obj:
No properties exp:
No properties

这下明白了吧,其实他就下面这种形式的缩写。

<ul>
{{#if obj}}
{{#each obj}}
<li>{{@key}}: {{this}}</li>
{{/each}}
{{else}}
<li>No properties</li>
{{/if}}
</ul>

{{#unless}}...{{else}}...{{/unless}}

这个跟if else相反,没什么好说的,感觉有些鸡肋,有了if else还造这玩意干啥?不懂

{{#with}}...{{/with}}

这个跟{{#each}}...{{/each}}差不多,也是个鸡肋,对比栗子如下:

    <p>with</p>
{{#with props}}
<p>Car has {{power}} power and {{speed}} maximum speed</p>
{{/with}} <p>each</p>
{{#each props}}
<p>Car has {{this}} {{@key}}</p>
{{/each}} var context = {
props: {
power: '150 hp',
speed: '200 km/h',
}
};
输出:
with
Car has 150 hp power and 200 km/h maximum speed each
Car has 150 hp power
Car has 200 km/h speed

{{#variableName}}...{{/variableName}}

If you pass a block expression with helper name that is in the
expression context, then it will work like {{#each}} helper for this
context if it is an Array, and will work like {{#with}} helper if it
is an Object:

以上是官方的解释,也就是根据传入数据的类型是对象还是数组自动的去执行。

<p>数组:</p>
<ul>
{{#people}}
<li>{{name}} - {{age}} years old</li>
{{/people}}
</ul>
<p>对象:</p>
{{#props}}
<p>Car has {{power}} power and {{speed}} maximum speed</p>
{{/props}}
<p>其他</p>
{{#title}}
<p>{{this}}</p>
{{/title}} people: [
{
name: 'John Doe',
age: 18
},
{
name: 'Mark Johnson',
age: 21
}
],
props: {
power: '150 hp',
speed: '200 km/h'
},
title: 'Friends' 输出:
数组:
John Doe - 18 years old
Mark Johnson - 21 years old 对象:
Car has 150 hp power and 200 km/h maximum speed 其他
Friends

这个方法看起来挺好用,但是我觉得会导致程序读起来不明确,出了错也不容易排查,还是觉得鸡肋。

{{escape}}

This plain helper returns escaped HTML string. It escapes only the following characters: < > " &

这个方法用来把几个特定的字符< > " &转码成HTML字符串,目前我还没想到在什么场景下需要转码。

<h1>{{title}}</h1>
<p>{{escape body}}</p> {
title: 'Paragraphs',
body: 'We need to use <p> tags to add paragraphs in HTML',
} <h1>Paragraphs</h1>
<p>We need to use &lt;p&gt; tags to add paragraphs in HTML</p>

{{js "expression"}}

js表达式,我觉得这个方法还是比较有用的,之前曾遇到一个问题,通过API后台传过来一堆内容,然后我把它全部填到模板里,但是,这些数据里有些内容,比如文件大小,传过来是字节的,我需要根据大小转成KB,MB,GB等单位,这一步还好,但是计算出来往往小数点后好多位,比如3.222222MB,模板当时用的jquery的,当时就懵逼了,只能去找后端。但是如果模板能够用js表达式的话,这个问题就能解决了。

<h3>{{title}}</h3>
<p>Price: ${{js "this.price * 1.2"}} </p>
<p>{{js "this.inStock ? 'In Stock' : 'Not in stock'"}} </p>
<p>{{js "this.number.toFixed(2)"}}</p> title: 'iPhone 6 Plus',
price: 1000,
inStock: true,
number:2.22222 输出:
iPhone 6 Plus
Price: $1200
In Stock
2.22

{{#js_compare "expression"}}...{{/js_compare}}

在我看来还不如if else用的顺手,鸡肋

<h3>{{title}}</h3>
<p>Price: ${{price}} </p>
<p>{{#js_compare "this.color === 'white' && this.memory > 16"}}Not in stock{{else}}In stock{{/js_compare}} </p>
<p>
{{#if "this.color === 'white' && this.memory > 16"}}
Not in stock
{{else}}
In stock
{{/if}}
</p> title: 'iPhone 6 Plus',
price: 1000,
color: 'white',
memory: 32 iPhone 6 Plus
Price: $1000
Not in stock
Not in stock

此外,template7还支持添加、删除自定义helpers,即根据需要扩展自己需要的方法,感觉也没啥卵用

Template7.registerHelper(name, helper)

Template7.unregisterHelper(name)

name - string - helper name
helper - function - helper function to handle passed context

还有几个不常用的方法,就不在说了,有兴趣自己去官网看一下。
总的来说,感觉template7里面重复的东西太多,之前有看过jquery-tmpl的源码才不到100行,underscore.js内置的模板好像70行以内。而它500行左右,搞了一堆七七八八的内容,但真正平常用到的只是少部分,如果让我用的话,我可能会去掉里面的一些内容再用,或者直接选用更加精简的模板引擎。
暂时先写到这里,有时间,再补充一点对源码的认识。

template7入门教程及对它的一些看法的更多相关文章

  1. wepack+sass+vue 入门教程(三)

    十一.安装sass文件转换为css需要的相关依赖包 npm install --save-dev sass-loader style-loader css-loader loader的作用是辅助web ...

  2. wepack+sass+vue 入门教程(二)

    六.新建webpack配置文件 webpack.config.js 文件整体框架内容如下,后续会详细说明每个配置项的配置 webpack.config.js直接放在项目demo目录下 module.e ...

  3. wepack+sass+vue 入门教程(一)

    一.安装node.js node.js是基础,必须先安装.而且最新版的node.js,已经集成了npm. 下载地址 node安装,一路按默认即可. 二.全局安装webpack npm install ...

  4. Content Security Policy 入门教程

    阮一峰文章:Content Security Policy 入门教程

  5. gulp详细入门教程

    本文链接:http://www.ydcss.com/archives/18 gulp详细入门教程 简介: gulp是前端开发过程中对代码进行构建的工具,是自动化项目的构建利器:她不仅能对网站资源进行优 ...

  6. UE4新手引导入门教程

    请大家去这个地址下载:file:///D:/UE4%20Doc/虚幻4新手引导入门教程.pdf

  7. ABP(现代ASP.NET样板开发框架)系列之2、ABP入门教程

    点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之2.ABP入门教程 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)” ...

  8. webpack入门教程之初识loader(二)

    上一节我们学习了webpack的安装和编译,这一节我们来一起学习webpack的加载器和配置文件. 要想让网页看起来绚丽多彩,那么css就是必不可少的一份子.如果想要在应用中增加一个css文件,那么w ...

  9. 转载:TypeScript 简介与《TypeScript 中文入门教程》

    简介 TypeScript是一种由微软开发的自由和开源的编程语言.它是JavaScript的一个超集,而且本质上向这个语言添加了可选的静态类型和基于类的面向对象编程.安德斯·海尔斯伯格,C#的首席架构 ...

随机推荐

  1. python 2.x 版本 pip 的使用

    看文档要使用 python2.7 的 pip 安装 TensorFlow, 因为有python3和pip3的缘故(pip2 和 /usr/bin/pip2看起来像是基于python2.x的,打个-V便 ...

  2. Qt:QMutex

    0.说明 QMutex类提供了线程间的同步控制. QMutex的目的是,保护Object.数据结构.代码块,以便每次只有一个线程能访问它(类似Java中的synchronized关键字).不过更好的情 ...

  3. JAVA ArrayList集合底层源码分析

    目录 ArrayList集合 一.ArrayList的注意事项 二. ArrayList 的底层操作机制源码分析(重点,难点.) 1.JDK8.0 2.JDK11.0 ArrayList集合 一.Ar ...

  4. DPLL 算法(求解k-SAT问题)详解(C++实现)

    \(\text{By}\ \mathsf{Chesium}\) DPLL 算法,全称为 Davis-Putnam-Logemann-Loveland(戴维斯-普特南-洛吉曼-洛夫兰德)算法,是一种完备 ...

  5. 『德不孤』Pytest框架 — 11、Pytest中Fixture装饰器(一)

    目录 1.Fixture装饰器的用途 2.Fixture参数说明 3.Fixture装饰器简单应用 4.yield执行后置函数 1.Fixture装饰器的用途 做测试前后的初始化设置,如测试数据准备, ...

  6. tp 防止xss攻击

    跨站脚本攻击(Cross Site Scripting),攻击者往Web页面里插入恶意Script代码,当用户浏览该页之时,嵌入其中Web里面的Script代码会被执行,从而达到恶意攻击用户的目的. ...

  7. How Do Vision Transformers Work?[2202.06709] - 论文研读系列(2) 个人笔记

    [论文简析]How Do Vision Transformers Work?[2202.06709] 论文题目:How Do Vision Transformers Work? 论文地址:http:/ ...

  8. 单循环链表(基于java语言)

    public class CircleSinglyLinkList { private Node head; CircleSinglyLinkList(){ this.head = null; } C ...

  9. python+pytest接口自动化(9)-cookie绕过登录(保持登录状态)

    在编写接口自动化测试用例或其他脚本的过程中,经常会遇到需要绕过用户名/密码或验证码登录,去请求接口的情况,一是因为有时验证码会比较复杂,比如有些图形验证码,难以通过接口的方式去处理:再者,每次请求接口 ...

  10. 什么是CPI

    请参考这篇博客,很全面的解释了CPI https://www.cnblogs.com/diegodu/p/9366639.html