High performance JavaScript templating engine

Overview

art-template

NPM Version NPM Downloads Node.js Version Travis-ci Coverage Status

English document | 中文文档

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.

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

chart

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)
  3. 支持 Express、Koa、Webpack
  4. 支持模板继承与子模板
  5. 浏览器版本仅 6KB 大小

捐助我(微信支付)

[AD] 前端招聘:在海边写代码

Comments
  • 渲染时,无法得到根目录下子目录中的文件并且无法渲染html后缀文件

    渲染时,无法得到根目录下子目录中的文件并且无法渲染html后缀文件

    问题1:无法得到根目录下子目录中的文件 目录结构

    —views
      ┴auth.art
    

    调用代码

    app.set('view options', {
        rule: rule,
        root: process.cwd() + '/views/',
        debug: true,
    });
    
    res.render('auth', {title: '测试标题'});
    

    但是如果目录结构改变一下

    —views
      ┴layout
          ┴auth.art
    

    调用代码

    app.set('view options', {
        rule: rule,
        root: process.cwd() + '/views/',
        debug: true,
    });
    
    res.render('layout/auth', {title: '测试标题'});
    res.render('/layout/auth', {title: '测试标题'});
    res.render('layout.auth', {title: '测试标题'});
    //三者均无法使用,前两者错误均为
    Failed to lookup view "layout/auth" in views directory "/root/views"
        at Function.render (/root/node_modules/express/lib/application.js:580:17)
        at ServerResponse.render (/root/node_modules/express/lib/response.js:971:7)
        at /root/core/http/route.js:51:9
    //第三者错误为
    Error: Cannot find module 'auth'
        at Function.Module._resolveFilename (module.js:485:15)
        at Function.Module._load (module.js:437:25)
        at Module.require (module.js:513:17)
        at require (internal/module.js:11:18)
        at new View (/root/node_modules/express/lib/view.js:80:30)
    

    问题2:无法渲染html后缀文件 调用代码

    app.set('view options', {
        rule: rule,
        root: process.cwd() + '/views/',
        debug: true,
        extname: '.html'
    });
    
    res.render('auth', {title: '测试标题'});
    //不管html文件在哪个目录,总之就是无法指定html后缀,如果加上html后缀就会有下面报错
    //如果不加后缀,那么会报错找不到auth 文件,根据错误分析应该是没有自动添加后缀
    

    错误为

    Cannot find module 'html'
        at Function.Module._resolveFilename (module.js:485:15)
        at Function.Module._load (module.js:437:25)
        at Module.require (module.js:513:17)
        at require (internal/module.js:11:18)
    
    opened by nishuzumi 17
  • template.defaults.imports 引用问题

    template.defaults.imports 引用问题

    你好 我现在遇到了一个问题,就是使用拦截器的时候必须在当前html内声明template.defaults.imports 拦截器才行,但是我现在是想把template.defaults.imports拦截器提出来一个js文件,其他页面想要用某一个方法直接引用js,这样能够提高复用性,在文档里面我没有看到关于这方面的介绍,请问是否有解决方法?谢谢

    opened by ka-zii 12
  • javascript 代码变量静态分析

    javascript 代码变量静态分析

    2013-09-06 更新

    上一版本的分析器包含两个BUG,导致模板逻辑语法中出现地雷:

    1. 无法正确处理特殊情况下的字符串 "\"" 或者 '\''
    2. 无法解析$号开头且后面为数字的变量,如 $0

    以下是新的解析器实现,完善字符串与数字判断的正则,解决上述两个BUG:

    // 静态分析模板变量
    var KEYWORDS =
        // 关键字
        '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'
    
        // ECMA 5 - use strict
        + ',arguments,let,yield'
    
        + ',undefined';
    
    var REMOVE_RE = /\/\*[\w\W]*?\*\/|\/\/[^\n]*\n|\/\/[^\n]*$|"(?:[^"\\]|\\[\w\W])*"|'(?:[^'\\]|\\[\w\W])*'|[\s\t\n]*\.[\s\t\n]*[$\w\.]+/g;
    var SPLIT_RE = /[^\w$]+/g;
    var KEYWORDS_RE = new RegExp(["\\b" + KEYWORDS.replace(/,/g, '\\b|\\b') + "\\b"].join('|'), 'g');
    var NUMBER_RE = /^\d[^,]*|,\d[^,]*/g;
    var BOUNDARY_RE = /^,+|,+$/g;
    
    var getVariable = function (code) {
    
        code = code
        .replace(REMOVE_RE, '')
        .replace(SPLIT_RE, ',')
        .replace(KEYWORDS_RE, '')
        .replace(NUMBER_RE, '')
        .replace(BOUNDARY_RE, '');
    
        code = code ? code.split(/,+/) : [];
    
        return code;
    };
    

    测试代码:

    // test
    var test = function () {
        /*tang bin*/
        // hello
        var $1, $1$, a$0, a$$, a0;
        var str = c$0 + 'fdsf\'hello';//word
        var $ = 7;
        var x = {};
        x.toString();
    
        var _me; _2, _;
    
        var $test = _2 > 399  || _3 < -235;
    
        return false;
    }.toString();
    
    console.log(getVariable(test))
    

    算法采用过滤的思路实现:

    1. 删除注释、字符串、方法名,这一步是为了排除干扰
    2. 删除可组成变量的字符,只保留字母、数字、美元符号与下划线,并进行分组
    3. 删除分组中的 js 关键字与保留字成员
    4. 删除分组中的数字成员

    经过四轮过滤后,剩下来的就是模板变量列表了,且不会有漏网之鱼,从而避免编译后的函数出现未定义的变量。当然,出于使用场景考虑,忽略了下面的两个问题:

    1. 没有排除对象字面量
    2. 没有排除正则表达式

    关于第2点,有个现实的问题是是:要完美区分正则与除法在不使用语法分析的情况下是无法实现的,引入 ast 成本过大。

    最后,默念一遍:没有完美的方案,只有最适合的方案。如有问题欢迎提出

    question 
    opened by aui 11
  • include使用art-template-loader引入外部子模板问题

    include使用art-template-loader引入外部子模板问题

    1. 错误描述

    1、header.art代码如下: image 引用header.art文件的body.art文件如下: image body.art中: <% include('./component/header.art', { title: title }) %> title值没有绘制成功; 2、body.art文件中的这段代码如何采用模板语法绘制 {{each responsedata value i}}

  • {{value.name}}
  • {{/each}} ,如何在js文件中使用? 目前调用的index.js如下: image 请问在最下面的draw函数中,如何使用body.art这个文件进行数据绘制?

    2. 版本号

    "art-template": "^4.9.1", "art-template-loader": "^1.4.2",

    3. NodeJS 或浏览器类型与版本

    nodejs -v6.2.0 google chrome 版本 58.0.3029.96 (64-bit)

    4. 可重现的 Demo

    Demo暂时无法重现,详情请看错误描述,谢谢

    opened by sjoooo123 9
  • TemplateError 在ie内核浏览器和一些移动端上

    TemplateError 在ie内核浏览器和一些移动端上

    在chrome下显示正常, 在ie内核和一部分手机上显示{ Template Error },

    在ie下报错如下: TemplateError { "name": "RuntimeError", "path": "activeTmpl", "message": "缺少对象", "line": 139, "column": 131, "source": "{{[value.Type,value.SubType] | typeRender}}" }

    数据源如下: [ { "ID": "40350003", "Type": "3", "SubType": "3", "Rank": "5", "Name": "祈愿塔罗牌", "Icon": "Item00_019", "Num": 5 }, { "ID": "", "Type": "99", "SubType": "", "Rank": "", "Name": "", "Icon": "", "Num": 300 } ]

    请问这是什么原因?

    opened by ShineMy 8
  • node版本和web版本的语法界定符冲突

    node版本和web版本的语法界定符冲突

    我用art-template-loader 的webpack loader加载器去打包渲染html,然后我在这个html里又有一个script标签,标签里还存放着我需要异步渲染的模版html,然后界定符冲突,node端的渲染已经把script标签里的模版给渲染了,导致script标签里的模版失效。

    后 main我又去看了下node版的art-template,发现没有提供修改rules的方法,我用加载器里的options的rules传了一个规则数组。发现会覆盖use方法,node端有没有类似web端的template.defaults.rules[0].test=xxxx 的方法呢?

    opened by theoldmoon 8
  • each时调用外层的数据可以吗?

    each时调用外层的数据可以吗?

    例:var data = { title : 'HELLO WORLD', isAdmin : true, list : ['新闻','军事','历史','政治'] }; 在each list时:{{each list}} {{$value}}

  • {{/each}} ,调用到与list同级的title(在each内部), 可以实现吗?语法是? 还是我不得不先把title放到list中,再调用each? 期待回复,谢谢!

opened by nikittaa 8
  • 在某些移动浏览器执行的时候,会导致模版错误,原因我已经找到,希望能采纳改进到代码里面。

    在某些移动浏览器执行的时候,会导致模版错误,原因我已经找到,希望能采纳改进到代码里面。

    // 提取模板中的变量名 function getKey (code) {

            code = getVariable(code);
    
            // 分词
            forEach(code, function (name) {
    
                // 除重
                if (!uniq.hasOwnProperty(name)&&name.length>0) {
    

    //add by hongfa.yy &&name.length>0 setValue(name); uniq[name] = true; }

            });
    
        }
    

    例如: <%shanks.each([1,2,3],function(index,item){%> 结束时间:<%=data.endTime%> <%});%>只有类似这种形式才会出问题,整个方法的{}被断开的时候。 <%shanks.each([1,2,3],function(index,item){}%>这样的形式是不会出问题。 以上情况出现错误只在i9100上面。

    opened by shanks-hongfa 8
  • 启用 html-minifier 压缩后,模板产生编译错误

    启用 html-minifier 压缩后,模板产生编译错误

    我有个如下模板

        <div class="user_s00000">
    
    	<style>
    	.J_ModuleWrap .user_s00000{ position:relative; z-index:5; background:url(//img13.360buyimg.com/zx/jfs/t1/22150/12/191/83743/5c07ab1bEdeb1f8e7/2be805357908913d.jpg) center center repeat; height:60px; }
    
    	/*-----  标题颜色 !固定的!  -----*/
    	.user_title_1{ color:#888888}
    	
    	/*-----  白色背景 !固定的!  -----*/
    	.user_bgcolor_3{ background-color:#ffff}
    	
    	/*-----  白色字体 !固定的!  -----*/
    	.user_color_3{color:#ffffff;}
    	
    	/*-----  一般无连接字体 !固定的!  -----*/
    	.user_color_5{color:#888888;}
    			
    	/*-----  标签颜色 !固定的!  -----*/
    	.user_color_6{color:#666666;}
    	
    	/*-----  边框颜色 !固定的!  -----*/
    	.user_border_1{border:1px solid #dedede;transition:all 0.4s ease;}
    	
    	 .user_border_bottom{ border-bottom:1px solid #dedede;}
             </style>
        </div>
    

    此模板在我mac上渲染正常,在线上Linux服务器上渲染失败,类似失败的模板还有很多,打断点发现

        if (minimize) {
            try {
                source = htmlMinifier(source, options);
            } catch (error) {}
        }
    

    这段代码前后,source的内容已经被格式化成错误的形式如下

         CompileError: Unexpected token )
        TemplateError: anonymous:1:1
         >> 1| <div class="user_s00000"><style>.J_ModuleWrap .user_s00000{position:relative;z-index:5;background:url(//img13.360buyimg.com/zx/jfs/t1/22150/12/191/83743/5c07ab1bEdeb1f8e7/2be805357908913d.jpg) center center repeat;height:60px}color:#888888 .user_bgcolor_3{background-color:#ffff}.user_color_3{color:#fff}.user_color_5{color:#888}.user_color_6{color:#666}.user_border_1{border:1px solid #dedede;transition:all .4s ease}.user_border_bottom{border-bottom:1px solid #dedede}.user_border_15{border:1px solid #dedede;transition:all .4s ease}.user_border_15:hover{border:1px solid #fff;transition:all .4s ease}.user_border_5{border:1px solid #dedede;transition:all .4s ease}.user_border_11{border:2px solid #888;transition:all .4s ease} {{if data[0].quanjucolor == '1' }} .user_bgcolor_1{background-color:#ec0c31}.user_bgcolor_2{background-color:#565656}.user_color_1{color:#ec0c31}.user_color_2{color:#565656}
    

    于是我把minimize设置成false,运行,线上就正确了。应该是html-minifier 在压缩代码的时候没有对系统中空格换行等特殊字符做兼容处理。

    opened by mailylqj 7
  • art-template-web在input type=checkbox时有解析bug

    art-template-web在input type=checkbox时有解析bug

    <input{{ value.status ? ' checked' : ''}} type="checkbox"> 上面这样写会报错 CompileError: Unexpected token = generated: $$out+=value.status="" ?="" 'checked'="" :="" ''

    opened by isszz 7
  • English Translation, please!

    English Translation, please!

    Hi!

    First of all, thanks for this great library. Unfortunately all documentations and information about it is in a language that for many people is totally impossible to understand...

    Do you plan to translate it to English some day? That's what is avoiding my company to adopt this great library.

    Thank you!

    opened by Javiani 7
  • {{@@item.value}} 在{{each }}中无效

    {{@@item.value}} 在{{each }}中无效

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>basic-demo</title>
    <script src="../../lib/template-web.js"></script>
    </head>
    
    <body>
    <div id="content"></div>
    <script id="test" type="text/html">
    <% if (isAdmin) { %>
    
    <h1><%=title%></h1>
    <ul>
        <% for (var i = 0; i < list.length; i ++) { %>
            <li>索引 <%= i + 1 %> :<%= list[i] %></li>
        <% } %>
    </ul>
    
    <% } %>
    
    data: <%=$data%>
    
    {{each list item i}}
    {{@item}}
    {{/each}}
    </script>
    
    <script>
    var data = {
    	title: '基本例子',
    	isAdmin: true,
    	list: ['文艺</br><p></p>', '博客', '摄影', '电影', '民谣', '旅行', '吉他']
    };
    var html = template('test', data);
    document.getElementById('content').innerHTML = html;
    </script>
    </body>
    </html>
    
    opened by ZevFung 0
  • 在 js 中配置模板,能使用 include 吗?

    在 js 中配置模板,能使用 include 吗?

    版本:v4.13.2 场景:树状菜单遍历 如果将模板放在页面中 <script> ,可以 include 自身的 id,达成目的。 但是需要放在公共部分,所以放在一个全局的 js 文件里,看示例 include 只有【模板ID】或者【文件路径】,能否支持传递模板变量?或者有其他方法? 示例:https://codepen.io/ciaoca/pen/RwVLpaa

    使用 <script> 配置模板

    <div id="box"></div>
    
    <script id="tmp_tree" type="text/html">
    <ul>
      {{each list item index}}
        <li>{{floor}}-{{item.title}}
          {{if item.children && item.children.length}}
            <% include('tmp_tree', {list: item.children, floor: floor+1}) %>
          {{/if}}
        </li>
      {{/each}}
    </ul>
    </script>
    
    <script>
    var data = [
      {
        title: 'a',
        children: [
          {
            title: 'a-1',
            children: [
              {
                title: 'a-1-1'
              },
              {
                title: 'a-1-2'
              }
            ]
          },
          {
            title: 'a-2'
          }
        ]
      },
      {
        title: 'b',
        children: [
          {
            title: 'b-1'
          },
          {
            title: 'b-2'
          }
        ]
      }
    ];
    var html = template('tmp_tree', {
      list: data,
      floor: 0
    });
    
    document.getElementById('box').innerHTML = html;
    </script>
    

    在 js 中配置模板

    var tmpTree = '<ul>'
      + '{{each list item index}}'
        + '<li class="floor_{{floor}}">{{floor}}-{{item.title}}'
          // + '{{if item.children && item.children.length}}'
          //   + '<% include('tmpTree', {list: item.children, floor: floor+1}) %>' // 这里怎样才能使用 include ?
          // + '{{/if}}'
        + '</li>'
      + '{{/each}}'
    + '</ul>';
    
    var render = template.compile(tmpTree);
    var html = render({
      list: data,
      floor: 0
    });
    console.log(html);
    
    opened by ciaoca 0
  • react项目通过 import artTemplate from

    react项目通过 import artTemplate from "art-template" 引入异常

    react版本: ^16.13.1 通过 import artTemplate from "art-template" 引入异常,定位代码

    const template = require('./lib/index'); const extension = require('./lib/extension');

    template.extension = extension;

    require.extensions[template.defaults.extname] = extension;

    module.exports = template;

    编译器提示require.extensions 已废弃,通过console打印require.extensions 为 undefined

    opened by niantuo 4
  • Help. 请教 vue2 项目中 如何 使用 cdn 引入 art-template 并使用?

    Help. 请教 vue2 项目中 如何 使用 cdn 引入 art-template 并使用?

    请问一下 cdn 引入, 使用还需要引入什么么,报错了 报错内容:

    ReferenceError: template is not defined
    

    我在vue2 项目的 index.html 中引入了cdn

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/index.min.js"></script>
    

    在 methods中使用:

    this.$refs.card.append(
      template('art-card', {
        message: '112312323'
      })
    )
    
    opened by radiorz 0
  • Releases(v4.13.2)
    AppRun is a JavaScript library for developing high-performance and reliable web applications using the elm inspired architecture, events and components.

    AppRun AppRun is a JavaScript library for building reliable, high-performance web applications using the Elm-inspired architecture, events, and compon

    Yiyi Sun 1.1k Dec 20, 2022
    High performance and SEO friendly lazy loader for images (responsive and normal), iframes and more, that detects any visibility changes triggered through user interaction, CSS or JavaScript without configuration.

    lazysizes lazysizes is a fast (jank-free), SEO-friendly and self-initializing lazyloader for images (including responsive images picture/srcset), ifra

    Alexander Farkas 16.6k Jan 1, 2023
    High performance JSX web views for S.js applications

    Surplus const name = S.data("world"), view = <h1>Hello {name()}!</h1>; document.body.appendChild(view); Surplus is a compiler and runtime to all

    Adam Haile 587 Dec 30, 2022
    Crawler Crypto using NodeJS for performance with Elasticsearch DB for high efficiency.

    Coin crawler - Coingecko version Crawler using NodeJS for performance with Elasticsearch DB for high efficiency. Requirements For development, you wil

    Minh.N.Pham 1 Jan 20, 2022
    High performance (de)compression in an 8kB package

    fflate High performance (de)compression in an 8kB package Why fflate? fflate (short for fast flate) is the fastest, smallest, and most versatile pure

    null 1.4k Dec 28, 2022
    startupDB is an Express middleware function implementing a high-performance in-memory database

    startupDB startupDB is a database designed to create REST APIs. It is implemented as an Express middleware function and allows for easy implementation

    Jeroen de Vries 8 Jul 26, 2022
    high performance、complex interaction table

    功能描述 1、高性能、满足复杂交互的编辑表格 2、基于: antd4(https://ant.design/index-cn) ag-grid(https://www.ag-grid.com/) 3、基于原生ag-grid 的API进行封装 一、主要功能 将按下列顺序逐步迭代 1、通用编辑功能 ??

    wheel-team 4 Feb 15, 2022
    🔑 Keagate is an open-source, high-performance alternative to popular cryptocurrency payment gateways such as Coinbase Commerce, CoinGate, BitPay, NOWPayments, CoinRemitter, CoinsPaid and more.

    ⛩️ Keagate – A High-Performance Cryptocurrency Payment Gateway ?? This project is actively in development ?? Table of Contents About the Project Purpo

    null 76 Jan 3, 2023
    An ultra-high performance stream reader for browser and Node.js

    QuickReader An ultra-high performance stream reader for browser and Node.js, easy-to-use, zero dependency. Install npm i quickreader Demo import {Quic

    EtherDream 156 Nov 28, 2022
    The brand new @shopify/flash-list high performance list component can be used on TV as well as on phones!

    FlashListTV The brand new @shopify/flash-list high performance list component can be used on TV as well as on phones! Quick start: Clone this repo Cha

    Douglas Lowder 4 Oct 27, 2022
    A TypeScript implementation of High-Performance Polynomial Root Finding for Graphics (Yuksel 2022)

    Nomial Nomial is a TypeScript implementation of Cem Yuksel's extremely fast, robust, and simple root finding algorithm presented in the paper "High-Pe

    Peter Boyer 10 Aug 3, 2022
    👑 A tiny yet powerful tool for high-performance color manipulations and conversions

    Colord is a tiny yet powerful tool for high-performance color manipulations and conversions. Features ?? Small: Just 1.7 KB gzipped (3x+ lighter than

    Vlad Shilov 1.2k Jan 3, 2023
    A scalable, high-performance feature management and progressive experimentation platform

    Introduction & Our Philosophy FeatBit is a scalable, high-performance Feature Management and Progressive Experimentation platform. Feature Management

    null 345 Jan 1, 2023
    High performance personalization & a/b testing example using Next.js, Edge Middleware, and Builder.io

    Next.js + Builder.io Personalization & A/B Testing with Edge Middleware This is a fork of Next.js Commerce with Builder.io integrated and using Edge M

    Builder.io 7 Sep 6, 2022
    The project integrates workflow engine, report engine and organization authority management background, which can be applied to the development of OA, HR, CRM, PM and other systems. With tlv8 IDE, business system development, testing and deployment can be realized quickly.

    介绍 项目集成了工作流引擎、报表引擎和组织机构权限管理后台,可以应用于OA、HR、CRM、PM等系统开发。配合使用tlv8 ide可以快速实现业务系统开发、测试、部署。 后台采用Spring MVC架构简单方便,前端使用流行的layui界面美观大方。 采用组件开发技术,提高系统的灵活性和可扩展性;采

    Qian Chen 38 Dec 27, 2022
    Seamless and lightweight parallax scrolling library implemented in pure JavaScript utilizing Hardware acceleration for extra performance.

    parallax-vanilla.js Seamless and lightweight parallax scrolling library implemented in pure JavaScript utilizing Hardware acceleration for extra perfo

    Erik Engervall 91 Dec 16, 2022
    Lexical is an extensible JavaScript web text-editor framework with an emphasis on reliability, accessibility and performance

    Lexical is an extensible JavaScript web text-editor framework with an emphasis on reliability, accessibility and performance. Lexical aims to provide a best-in-class developer experience, so you can easily prototype and build features with confidence.

    Meta 12.7k Dec 30, 2022
    High-quality QR Code generator library in Java, TypeScript/JavaScript, Python, Rust, C++, C.

    QR Code generator library Introduction This project aims to be the best, clearest QR Code generator library in multiple languages. The primary goals a

    Nayuki 3.3k Jan 4, 2023
    High-order Virtual Machine (HVM) wrapper on JavaScript, via WASM

    HVM on JavaScript HVM is now available as a JavaScript library! Installing npm i --save hvm-js Examples Evaluating a term to normal form import hvm fr

    null 14 Nov 24, 2022