artTemplate
新一代 javascript 模板引擎
=================
artTemplate 是新一代 javascript 模板引擎,它在 v8 中的渲染效率可接近 javascript 性能极限,在 chrome 下渲染效率测试中分别是知名引擎 Mustache 与 micro tmpl 的 25 、 32 倍(性能测试)。
引擎支持调试。若渲染中遇到错误,调试器可精确定位到产生异常的模板语句,解决前端模板难以调试的问题(详情)。
另外,artTemplate 的模板还支持使用自动化工具预编译,这一切都在 2KB(Gzip) 中实现!
快速上手
编写模板
使用一个type="text/html"的script标签存放模板:
<script id="test" type="text/html"> <h1><%=title%></h1> <ul> <%for(i = 0; i < list.length; i ++) {%> <li>条目内容 <%=i + 1%> :<%=list[i]%></li> <%}%> </ul></script>
模板逻辑语法开始与结束的界定符号为94f6aca98b9cef87407d2eca8edd2f7e,若41b41b457b6b72d521b1cc5aadc49358语句可以嵌入子模板,其中第二个参数是可选的,它默认传入当前的数据。
<script id="test" type="text/html"> <h1><%=title%></h1> <%include('list')%></script> <script id="list" type="text/html"> <ul> <%for(i = 0; i < list.length; i ++) {%> <li>条目内容 <%=i + 1%> :<%=list[i]%></li> <%}%> </ul></script>
演示
不转义HTML
模板引擎默认数据包含的 HTML 字符进行转义以避免 XSS 漏洞,若不需要转义的地方可使用==。
<script id="test" type="text/html"> <%==value%></script>
若需要关闭默认转义,可以设置template.isEscape = false。
演示
在js中存放模板
template.compile([id], source)将返回一个渲染函数。其中 id 参数是可选的,如果使用了 id 参数,可以使用template.render(id, data)渲染模板。
var source = '<ul>' + '<% for (var i = 0; i < list.length; i ++) { %>' + '<li>索引 <%= i + 1 %> :<%= list[i] %></li>' + '<% } %>' + '</ul>'; var data = { list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他'] }; var render = template.compile(source); var html = render(data); document.getElementById('content').innerHTML = html;
演示
添加辅助方法
template.helper(name, callback)辅助方法一般用来进行字符串替换,如 UBB 替换、脏话替换等。
例如扩展一个UBB替换方法:
template.helper('$ubb2html', function (content) { return content .replace(/[b]([^[]?)[/b]/igm, '<b>$1</b>') .replace(/[i]([^[]?)[/i]/igm, '<i>$1</i>') .replace(/[u]([^[]?)[/u]/igm, '<u>$1</u>') .replace(/[url=([^]])]([^[]?)[/url]/igm, '<a href="$1">$2</a>') .replace(/[img]([^[]?)[/img]/igm, '<img src="/static/imghwm/default1.png" data-src="$1" class="lazy" / alt="javascript template engine artTemplate" >'); });
在模板中的使用方式:
<%=$ubb2html(content) %>
注意:引擎不会对辅助方法输出的 HTML 字符进行转义。
演示
设置界定符
若前端模板语法与后端语法产生冲突,可以修改模板引擎界定符,例如:
template.openTag = "<!--["; template.closeTag = "]-->";
演示
自定义语法
artTemplate 提供一个语法扩展用来简化模板逻辑语法。语法示例:
{{if admin}} <h3 id="title">{{title}}</h3> <ul> {{each list}} <li>{{$index + 1}}: {{$value}}</li> {{/each}} </ul>{{/if}}
安装:把 extensions/template-syntax.js 合并到 template.js 底部。
更多语法说明
自动化工具
预编译工具
使用它可以让前端模版不再受浏览器的限制,支持如后端模版一样按文件放置、include 语句等特性,可以像后端一样书写前端模板!
编译后的模板不再依赖前端模板引擎与后端,模板可以通过 SeaJS 或 RequireJS 等加载器进行异步加载,亦能利用它们成熟的打包合并工具进行上线前的优化,如合并与压缩。
项目主页:
抽取工具
./tools/combine.html
可以把 HTML 中的模板提取出来以便把模板嵌入到 js 文件中。
与编译工具不同的是,抽取后的模板仍然依赖引擎运行。
模板编码规范
1、不能使用 javascript 关键字作为模板变量(包括 ECMA5 严格模式下新增的关键字):
> break, case, catch, continue, debugger, default, delete, do, else, false, finally, for, function, if, in, instanceof, new, null, return, switch, this, throw, true, try, typeof, var, void, while, with, abstract, boolean, byte, char, class, const, double, enum, export, extends, final, float, goto, implements, import, int, interface, long, native, package, private, protected, public, short, static, super, synchronized, throws, transient, volatile, arguments, let, yield
2、模板运行在沙箱中,内部无法访问外部变量,除非给模板定义辅助方法。例如:
template.helper('Math', Math)
> 模板中若任意引用外部对象,复杂的依赖管理将会让项目难以维护,这种方式将利于后续模板迁移(包括通过工具预编译)。
所有演示例子 | 引擎原理
以上就是javascript 模板引擎artTemplate的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)