GithubHelp home page GithubHelp logo

chengyifan / art-template Goto Github PK

View Code? Open in Web Editor NEW

This project forked from aui/art-template

0.0 2.0 0.0 3.9 MB

性能卓越的 js 模板引擎

License: MIT License

JavaScript 92.20% HTML 7.77% Smarty 0.02%

art-template's Introduction

art-template

NPM Version Node.js Version Travis-ci Coverage Status

art-template 是一个性能出众模板引擎,无论在 NodeJS 还是在浏览器中都可以运行。

chart

在线速度测试

特性

  • 针对 V8 引擎优化,渲染速度出众
  • 支持编译、运行时调试,可定位语法、渲染错误的模板语句
  • 支持 NodeJS 与 浏览器。支持 Express、Koa、Webpack、RequireJS
  • 支持模板包含与模板继承
  • 兼容 EJSUnderscoreLoDash 模板语法
  • 支持 ES 严格模式环境运行
  • 同时支持原生 JavaScript 语法、简约语法
  • 支持定义模板的语法规则
  • 浏览器版本仅 5KB 大小

安装

npm install art-template --save

快速入门

模板语法

<% if (user) { %>
  <h2><%= user.name %></h2>
<% } %>

或:

{{if user}}
  <h2>{{user.name}}</h2>
{{/if}}

NodeJS

var template = require('art-template');
var html = template(__diranme + '/tpl-user.art', {
    user: {
        name: 'aui'
    }
});

框架支持:

Webpack

安装 art-template-loader

var render = require('./tpl-user.art');
var html = render({
    user: {
        name: 'aui'
    }
});

Web

使用浏览器版本:lib/template-web.js

<script id="tpl-user" type="text/html">
<% if (user) { %>
  <h2><%= user.name %></h2>
<% } %>
</script>

<script src="art-template/lib/template-web.js"></script>
<script>
var html = template('tpl-user', {
    user: {
        name: 'aui'
    }
});
</script>

lib/template-web.js 支持 RequireJS 加载

核心方法

// 基于模板名渲染模板
template(filename, data);

// 将模板源代码编译成函数
template.compile(source, options);

// 将模板源代码编译成函数并立刻执行
template.render(source, data, options);

语法

art-template 同时支持 {{expression}} 简约语法与任意 JavaScript 表达式 <% expression %>

输出

1. 标准输出

{{value}}
{{a ? b : c}}
{{a || b}}
{{a + b}}

or

<%= value %>
<%= a ? b : c %>
<%= a || b %>
<%= a + b %>

特殊变量可以使用下标方式访问:

{{$data['user list']}}

2. 原始输出

{{@value}}

or

<%- value %>

原始输出语句不会对 HTML 内容进行转义

条件

{{if value}} ... {{/if}}
{{if v1}} ... {{else if v2}} ... {{/if}}

or

<% if (value) { %> ... <% } %>
<% if (value) { %> ... <% } else { %> ... <% } %>

循环

{{each target}}
    {{$index}} {{$value}}
{{/each}}

or

<% for(var i = 0; i < target.length; i++){ %>
    <%= i %> <%= target[i] %>
<% } %>
  1. target 支持 ArrayObject 的迭代,其默认值为 $data
  2. $value$index 可以自定义:{{each target val key}}

变量

{{set temp = data.sub.content}}

or

<% var temp = data.sub.content; %> 

子模板

{{include './header.art'}}
{{include './header.art' data}}

or

<% include('./header.art') %>
<% include('./header.art', data) %>

include 第二个参数默认值为 $data

布局

{{extend './layout.art'}}
{{block 'head'}} ... {{/block}}

模板继承允许你构建一个包含你站点共同元素的基本模板“骨架”。

范例

layout.art:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>{{block 'title'}}My Site{{/block}}</title>

    {{block 'head'}}
    <link rel="stylesheet" href="main.css">
    {{/block}}
</head>
<body>
    {{block 'content'}}{{/block}}
</body>
</html>

index.art:

{{extend './layout.art'}}

{{block 'title'}}My Page{{/block}}

{{block 'head'}}
    {{@parent}}
    <link rel="stylesheet" href="custom.css">
{{/block}}

{{block 'content'}}
<p>This is just an awesome page.</p>
{{/block}}

渲染 index.art 后,将自动应用布局骨架。

print

<% print(val, val2, val3) %>

过滤器

// 向模板中导入过滤器
template.defaults.imports.$dateFormat = function(date, format){/*[code..]*/};
template.defaults.imports.$timestamp = function(value){return value * 1000};
{{date | $timestamp | $dateFormat 'yyyy-MM-dd hh:mm:ss'}}

or

<%= $dateFormat($timestamp(date), 'yyyy-MM-dd hh:mm:ss') %>

全局变量

内置变量

  • $data 传入模板的数据 {Object|array}
  • $imports 外部导入的所有变量,等同 template.defaults.imports {Object}
  • $options 模板编译选项 {Object}
  • print 字符串输出函数 {function}
  • include 子模板载入函数 {function}
  • extend 布局模板导入函数 {function}
  • block 模板块声明函数 {function}

注入全局变量

template.defaults.imports.$console = console;
<% $console.log('hello world') %>

模板外部所有的变量都需要使用 template.defaults.imports 注入、并且要在模板编译之前进行声明才能使用。

缓存

缓存默认是开启的,开发环境中可以关闭它:

template.defaults.cache = false;

定义语法规则

从一个简单的例子说起,让模板引擎支持 ES6 ${name} 模板字符串的解析:

template.defaults.rules.push({
    test: /\${([\w\W]*?)}/,
    use: function(match, code) {
        return {
            code: code,
            output: 'escape'
        }
    }
});

其中 test 是匹配字符串正则,use 是匹配后的调用函数。关于 use 函数:

  • 参数:一个参数为匹配到的字符串,其余的参数依次接收 test 正则的分组匹配内容
  • 返回值:必须返回一个对象,包含 codeoutput 两个字段:
    • code 转换后的 JavaScript 语句
    • output 描述 code 的类型,可选值:
      • 'escape' 编码后进行输出
      • 'raw' 输出原始内容
      • false 不输出任何内容

使用 require(templatePath)

加载 .art 模板:

var template = require('art-template');
var view = require('./index.art');
var html = view(data); 

加载 .ejs 模板:

var template = require('art-template');
require.extensions['.ejs'] = template.extension;

var view = require('./index.ejs');
var html = view(data); 

API

template(filename, data)

根据模板名渲染模板。

var html = template('/welcome.art', {
    value: 'aui'
});

在浏览器中,filename 请传入存放模板的元素 id

template(filename, source)

编译模板并缓存。

// compile && cache
template('/welcome.art', 'hi, <%=value%>.');

// use
template('/welcome.art', {
    value: 'aui'
});

.compile(source, options)

编译模板并返回一个渲染函数。

var render = template.compile('hi, <%=value%>.');
var html = render({value: 'aui'});

.render(source, data, options)

编译并返回渲染结果。

var html = template.render('hi, <%=value%>.', {value: 'aui'});

.defaults

模板引擎默认配置。参考 选项

选项

template.defaults

{
    // 模板名字
    filename: null,

    // 模板语法规则列表
    rules: [nativeRule, artRule],

    // 是否支持对模板输出语句进行编码。为 false 则关闭编码输出功能
    escape: true,

    // 是否开启调试模式。如果为 true: {bail:false, cache:false, compileDebug:true}
    debug: false,

    // 是否开启缓存
    cache: true,

    // 是否编译调试版。编译为调试版本可以在运行时进行 DEBUG
    compileDebug: false,

    // 是否容错。如果为 true,编译错误与运行时错误都会抛出异常
    bail: false,

    // 模板路径转换器
    resolveFilename: resolveFilename,

    // HTML 压缩器
    compressor: null,

    // 错误调试器
    debuger: debuger,

    // 模板文件加载器
    loader: loader,

    // 缓存中心适配器(依赖 filename 字段)
    caches: caches,

    // 模板根目录。如果 filename 为全局路径,则会基于此查找模板
    root: '/',

    // 默认后缀名。如果没有后缀名,则会自动基于此补全
    extname: '.art',

    // 导入的模板变量
    imports: {
        $each: each,
        $escape: escape,
        $include: include
    }
};

兼容性

  1. NodeJS v1.0+
  2. IE9+(小于 IE9 需要 es5-shimJSON 支持)

授权协议

MIT

art-template's People

Contributors

antife-yinyue avatar aui avatar dongyingzi avatar erik168 avatar lienjun avatar wangxiao avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.