# Technical Documentation: goofychris/art-template

> ℹ️ **Provenance:** Hybrid Fusion: `goofychris/art-template` + `goofychris/art-template-docs` · [CodeWiki Reference](https://codewiki.google/github.com/goofychris/art-template) · Recency: Active (< 180 days)

## 1. Project Overview & Quickstart (goofychris/art-template)

> ## ⚠️ 项目已停止维护 / No Longer Maintained
>
> **中文：**
> 由于精力有限，无法继续投入维护，本项目自 2026 年 7 月 13 日起停止维护，
> 不再提供任何功能更新、问题修复或安全补丁。
> 请勿在生产环境中继续使用本项目，并尽快迁移到其他仍在积极维护的替代方案。
> 仍在依赖本项目的用户，建议尽早移除或替换该依赖。
> 感谢一直以来的使用与支持。
>
> **English:**
> Due to limited time and capacity, this project is no longer maintained
> as of July 13, 2026. It will receive no further feature updates, bug fixes,
> or security patches. Please do not use it in production, and migrate to an
> actively maintained alternative as soon as possible. Projects that still
> depend on it are strongly advised to remove or replace this dependency.
> Thank you for your past use and support.
> 
# art-template

[](https://npmjs.org/package/art-template)
[](https://npmjs.org/package/art-template)
[](http://nodejs.org/download/)
[](https://travis-ci.org/aui/art-template)
[](https://coveralls.io/github/aui/art-template?branch=master)

[English document](https://goofychris.github.io/art-template/) | [中文文档](https://goofychris.github.io/art-template/zh-cn/index.html)

art-template is a simple and superfast templating engine that optimizes template rendering speed by scope pre-declared technique, hence achieving runtime performance which is close to the limits of JavaScript. At the same time, it supports both NodeJS and browser. [speed test online](https://goofychris.github.io/art-template/rendering-test/).

art-template 是一个简约、超快的模板引擎。它采用作用域预声明的技术来优化模板渲染速度，从而获得接近 JavaScript 极限的运行性能，并且同时支持 NodeJS 和浏览器。[在线速度测试](https://goofychris.github.io/art-template/rendering-test/)。

[](https://goofychris.github.io/art-template/rendering-test/)

## Feature

1. performance is close to the JavaScript rendering limits
2. debugging friendly. Syntax errors or runtime errors will be positioned accurately at which line of template. Support setting breakpoint in templating files (Webpack Loader)
3. support Express, Koa, Webpack
4. support template inheritance and sub template
5. browser version is only 6KB

## 特性

1. 拥有接近 JavaScript 渲染极限的的性能
2. 调试友好：语法、运行时错误日志精确到模板所在行；支持在模板文件上打断点（Webpack Loader）
5. 支持 Express、Koa、Webpack
6. 支持模板继承与子模板
7. 浏览器版本仅 6KB 大小

## 2. Official Technical Reference & Guides (goofychris/art-template-docs)

## File: source/docs/api.md

---
title: API
categories: docs
comments: false
---

## template(filename, content)

Render templates according to template name.

* **Parameters**：
    * `{string} filename`
    * `{Object,string} content`
* **Return**：
    * if `content` is `Object`，render template and return `string`
    * if `content` is `string`，compile template and return `function`

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

> browser version can not load external file. `filename` is the element `id` of template

**Examples**

Compile templates and cache it.

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

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

## .compile(source, options)

Compile templates and return a rendering function.

* **Parameters**：
    * `{string} source`
    * `{Object} options`
* **Return**：`{function}`

**Examples**

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

## .render(source, data, options)

Compile and return rendering results.

* **Parameters**：
    * `{string} source`
    * `{Object} options`
* **Return**：`{string}`

**Examples**

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

## .defaults

Default configuration of template engine. Refer to [Options](./options.html).

* **Type**：`{Object}`

## .extension

Template rendering function registering for NodeJS `require.extensions`.

* **Type**：`{Object}`

**Examples**

Load `.ejs` templates:

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

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

`.art` is registered by default and you can use it directly:

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

It should be noted that this functionality only works for NodeJS. If you want to use template rendering functionality, please use Webpack [art-template-loader](../webpack).

---

## File: source/docs/debug.md

---
title: Debug
categories: docs
comments: false
---

`template.defaults.debug`

art-template has built-in debugger. It can catch syntax and runtime errors. In addition, it supports custom syntax. In NodeJS, debugging mode will be automatically opened according to the environment variable: `process.env.NODE_ENV !== 'production'`

Setting `template.defaults.debug=true` is equivalent to:

```json
{
    "cache": false,
    "minimize": false,
    "compileDebug": true
}
```

More for [options](./options.html).

---

## File: source/docs/imports.md

---
title: Template variable
categories: docs
comments: false
---

`template.defaults.imports`

Template can access global variable outside it and imported variable through `$imports`.

## Import variable

```js
template.defaults.imports.log = console.log;
```

```html
<% $imports.log('hello world') %>
```

## Built-in variable

* `$data`     the data passed into template
* `$imports`  variable imported from outside and global variable
* `print`     string-output function
* `include`   sub-template loading function
* `extend`    template-import function in template inheritance 
* `block`     template-block declaration function

---

## File: source/docs/index.md

---
title: Introduction
categories: docs
comments: false
---
art-template is a simple and superfast templating engine that optimizes template rendering speed by scope pre-declared technique, hence achieving runtime performance which is close to the limits of JavaScript. At the same time, it supports both NodeJS and browser. [speed test online](../rendering-test/).

## Feature

1. performance is close to the JavaScript rendering limits
2. debugging friendly. Syntax errors or runtime errors will be positioned accurately at which line of template. Support setting breakpoint in templating files (Webpack Loader)
3. support Express, Koa, Webpack
4. support template inheritance and sub template
5. browser version is only 6KB

## Template

art-template simultaneously supports two syntax of template. Standard syntax allows templates to be easier to read and write. While original syntax has powerful logical processing ability.

**standard syntax**

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

**original syntax**

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

Original syntax is compatible with [EJS](http://ejs.co), [Underscore](http://underscorejs.org/#template), [LoDash](https://lodash.com/docs/#template) templates.

## Render template

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

## Core method

```js
// render template basing on template name
template(filename, data);

// compile source of template as function
template.compile(source, options);

// compile source of template as function and immediately invoke it
template.render(source, data, options);
```

---

## File: source/docs/installation.md

---
title: Installation
categories: docs
comments: false
---

## Npm

```bash
npm install art-template --save
```

## Real-time compilation in browser

download：[template-web.js](https://unpkg.com/art-template/lib/template-web.js)（gzip: 6kb）

**compatibility**

IE8+（IE8 needs patch for execution. [example](https://github.com/aui/art-template/blob/master/example/web-ie-compatible/index.html)）

**difference**

Because browser doesn't support file system, so `template(filename, data)` doesn't support passing in file paths, and inside the method it uses `document.getElementById(filename).innerHTML` to obtain templates. For instance:

```html
<script src="lib/template-web.js"></script>
<script id="tpl-user" type="text/html">
{{if user}}
  <h2>{{user.name}}</h2>
{{/if}}
</script>
```

## Pre-compilation in browser

use loader of webpack: [art-template-loader](../webpack).

## Plugins

* Webpack: [art-template-loader](../webpack)
* Express: [express-art-template](../express)
* Koa: [koa-art-template](../koa)

---

## File: source/docs/minimize.md

---
title: Minimize
categories: docs
comments: false
---

`template.defaults.minimize`

Built-in minifier of art-template can minimize HTML, JS and CSS, which happens in compilation phase. So it totally has no effect on rendering speed and moreover speeds up network transmission.

## Minimize mode

```js
template.defaults.minimize = true;
```

## Configuration

Refer to: <https://github.com/kangax/html-minifier>

**default configuration**

```js
template.defaults.htmlMinifierOptions = {
    collapseWhitespace: true,
    minifyCSS: true,
    minifyJS: true,
    // automatically merged at runtime: rules.map(rule => rule.test)
    ignoreCustomFragments: []
};
```

---

## File: source/docs/options.md

---
title: Options
categories: docs
comments: false
---

`template.defaults`

```js
// template name
filename: null,

// an array of rules of template syntax
rules: [nativeRule, artRule],

// whether to automatically encode output statements of template. Setting false will close that functionality
// escape can prevent XSS attacks
escape: true,

// enable debug mode. If true: {cache:false, minimize:false, compileDebug:true}
debug: detectNode ? process.env.NODE_ENV !== 'production' : false,

// if bail is set true, compilation errors and runtime errors will throw exception
bail: true,

// whether to enable caching
cache: true,

// whether to enable minimization. It will execute htmlMinifier and minimize HTML, CSS, JS
// if template contains unclosing tags, please don't open minimize. Otherwise unclosing tags will be restored or filtered
minimize: true,

// whether to compile in debug mode
compileDebug: false,

// resolve template path
resolveFilename: resolveFilename,

// sub template compilation adapter
include: include,

// HTML minifier. Work only in NodeJS environment
htmlMinifier: htmlMinifier,

// HTML minifier configuration. Refer to: https://github.com/kangax/html-minifier
htmlMinifierOptions: {
    collapseWhitespace: true,
    minifyCSS: true,
    minifyJS: true,
    // automatically merged at runtime: rules.map(rule => rule.test)
    ignoreCustomFragments: []
},

// error events. Work only if bail is false
onerror: onerror,

// template file loader
loader: loader,

// cache center adapter (depend on filename field)
caches: caches,

// root directory of template. If filename field is not a local path, template will be found in root directory
root: '/',

// default extension. If no extensions, extname will be automatically added
extname: '.art',

// ignored variables. An array of template variables ignored by template compiler
ignore: [],

// imported template variables
imports: runtime
```

---

## File: source/docs/rules.md

---
title: Parsing rules
categories: docs
comments: false
---

`template.defaults.rules`

You can customize template parsing rules in art-template. Standard syntax and orginal syntax is configured by default.

## Modify delimiters

```js
// delimiter rules of original syntax
template.defaults.rules[0].test = /<%(#?)((?:==|=#|[=-])?)[ \t]*([\w\W]*?)[ \t]*(-?)%>/;
// delimiter rules of standard syntax
template.defaults.rules[1].test = /{{([@#]?)[ \t]*(\/?)([\w\W]*?)[ \t]*}}/;
```

They are regular expressions and you can only modify the delimiter part. For example, modify `<%` `%>` to `<?` `?>`:

```js
var rule = template.defaults.rules[0];
rule.test = new RegExp(rule.test.source.replace('<%', '<\\\?').replace('%>', '\\\?>'));
```

## Add syntax

Let's start with a simple example that make template engine support parse of template strings `${name}` of ES6:

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

`test` is a regular expression which matches strings and `use` is a callback function after matching. About `use` function:

* parameters: first parameter is the matching string, and others are content of capturing group of `test` regular expression
* return value: MUST return an object containing `code` and `output` properties:
    * `code` transformed JavaScript statements 
    * `output` describe type of `code`, optional value:
        * `'escape'` output after encoding
        * `'raw'` output raw content
        * `false` output nothing

It's worth mentioning that syntax rules have no effect on rendering speed and template parser will help you optimize rendering performance.

---

## File: source/zh-cn/docs/api.md

---
title: API
categories: docs
comments: false
---

## template(filename, content)

根据模板名渲染模板。

* **参数**：
    * `{string} filename`
    * `{Object,string} content`
* **返回值**：
    * 如果 `content` 为 `Object`，则渲染模板并返回 `string`
    * 如果 `content` 为 `string`，则编译模板并返回 `function`

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

> 浏览器版本无法加载外部文件，`filename` 为存放模板的元素 `id`

**示例**

编译模板并缓存。

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

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

## .compile(source, options)

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

* **参数**：
    * `{string} source`
    * `{Object} options`
* **返回值**：`{function}`

**示例**

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

## .render(source, data, options)

编译并返回渲染结果。

* **参数**：
    * `{string} source`
    * `{Object} options`
* **返回值**：`{string}`

**示例**

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

## .defaults

模板引擎默认配置。参考 [选项](./options.html)。

* **类型**：`{Object}`

## .extension

给 NodeJS `require.extensions` 注册的模板渲染函数。 

* **类型**：`{Object}`

**示例**

加载 `.ejs` 模板：

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

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

`.art` 默认被注册，可以直接使用：

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

需要注意的是：此功能仅对 NodeJS 生效，如果要在浏览器中使用模板文件渲染功能，请使用 Webpack [art-template-loader](../webpack)。

---

## File: source/zh-cn/docs/debug.md

---
title: 调试
categories: docs
comments: false
---

`template.defaults.debug`

art-template 内建调试器，能够捕获到语法与运行错误，并且支持自定义的语法。在 NodeJS 中调试模式会根据环境变量自动开启：`process.env.NODE_ENV !== 'production'`

设置 `template.defaults.debug=true` 后，等同于：

```json
{
    "cache": false,
    "minimize": false,
    "compileDebug": true
}
```

更多参见 [选项](./options.html)。

---

## File: source/zh-cn/docs/imports.md

---
title: 模板变量
categories: docs
comments: false
---

`template.defaults.imports`

模板通过 `$imports` 可以访问到模板外部的全局变量与导入的变量。

## 导入变量

```js
template.defaults.imports.log = console.log;
```

```html
<% $imports.log('hello world') %>
```

## 内置变量清单

* `$data`     传入模板的数据
* `$imports`  外部导入的变量以及全局变量
* `print`     字符串输出函数
* `include`   子模板载入函数
* `extend`    模板继承模板导入函数
* `block`     模板块声明函数

--- METRICS ---
- Files Extracted: 12
- Estimated Token Budget: ~4223 tokens
- Recency Window: Active (< 180 days)
- Canonical Reference: https://codewiki.google/github.com/goofychris/art-template
