Giter Site home page Giter Site logo

yanhaijing / template.js Goto Github PK

View Code? Open in Web Editor NEW
1.3K 50.0 499.0 3.65 MB

A javascript template engine, simple, easy & extras, support webpack, rspack, vite, rollup, esbuild, parcel, browserify, fis and gulp.

License: MIT License

JavaScript 94.46% HTML 4.19% CSS 0.21% TypeScript 1.07% Shell 0.08%
tmpl arttemplate templatejs baidutemplate juicer handlebars jade fis parcel rollup

template.js's Introduction

license CI

English | 简体中文

A javascript template engine that is simple, easy to use, and supports webpack, rspack, vite, esbuild, rollup, parcel, browserify, fis, and gulp.

Features

  • Native JS syntax, template parsing, compilation, and rendering
  • Supports all browsers and Node, supports TypeScript
  • Precompilation supports mainstream packaging tools
  • Custom configurations, decorators, and functions
  • Data filtering support
  • Exception capture functionality
  • Subtemplates
  • Sandbox mode
  • Supports JIT and AOT compilation modes
  • Provides CLI integrated tools
  • Provides support for editor plugins

User Guide

template.js is a better way than concatenating strings, Click to use codesandbox for a quick demo

Template example

<ul>
    <%for(var i = 0; i < list.length; i++) {%>
        <li><%:=list[i].name%></li>
    <%}%>
</ul>

Data example

const data = {
  list: [{ name: 'yan' }, { name: 'haijing' }],
};

Render output

<ul>
  <li>yan</li>
  <li>haijing</li>
</ul>

Editor plugins supported by template.js

Editor Plugin
Vscode highlight plugin
Sublime highlight plugin
Atom highlight plugin
WebStorm TODO

Quickly initialize a project using CLI tools

$ npx @templatejs/cli new myapp
# Choose the corresponding platform
# ❯ webpack
#   rspack
#   vite
#   rollup
#   esbuild
#   parcel2
#   parcel1
#   fis3
#   browserify
#   gulp
#   browser

If you already have a project, you can choose a corresponding plugin, template.js supports different usage methods

Platform Plugin
webpack / rspack template-loader
vite / rollup rollup-plugin-templatejs
esbuild esbuild-plugin-templatejs
parcel2 parcel-transformer-template
parcel1 parcel-plugin-template
fis fis-parser-template
browserify browserify-templatejs
gulp gulp-templatejs
Native web & Node.js template_js
Unsupported platforms You can write a plugin yourself, please see @templatejs/precompiler

Other packages summary

Developer Guide

This project uses lerna to manage multiple plugins. Common lerna commands are as follows, note that the npx prefix cannot be left out:

$ npx lerna init # Initialize
$ npx lerna create @templatejs/parser # Create a package
$ npx lerna add yargs --scope=@templatejs/parser # Install package dependencies
$ npx lerna list # List all packages
$ npx lerna bootstrap # Install all dependencies
$ npx lerna link # Create all soft links
$ npx lerna changed # List the packages to be updated next time when using lerna publish
$ npx lerna publish # Will tag, upload git, upload npm

Release steps, modify changelog

$ yarn lint
$ yarn build
$ yarn test
$ npx lerna publish

Release without tagging, suitable for test package.

$ yarn lint
$ yarn build
$ yarn test
$ lerna version --no-git-tag-version
$ npx lerna publish from-package --dist-tag next

Contributors List

contributors

Changelog

CHANGELOG.md

Planned Feature List

TODO.md

Who is Using

To learn about who is using this, click here.

Related Links

template.js's People

Contributors

davimeta avatar walkskyer avatar yanhaijing avatar yujiangshui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

template.js's Issues

templatejs-loader当tmpl模板文件使用CRLF换行时会出现Unexpected token ILLEGAL错误

templatejs-loader当tmpl模板文件使用CRLF换行时会出现Unexpected token ILLEGAL错误

windows环境, 开发软件是VSCode, 当我内容的换行方式是CRLF换行时会出现Unexpected token ILLEGAL的报错, 切换为LF换行方式后,正常.

image

环境

  • 系统: window 10
  • 浏览器:Chrome 78
  • 版本:2.0.0
  • 用到的插件: @template/runtime, templatejs-loader, webpack4
  • 其他信息

在线例子

测试的代码和webpack配置均使用的loader里面提供的webpack4的配置

相关依赖

"devDependencies": {
    "templatejs-loader": "^2.2.0"
  },
  "dependencies": {
    "@templatejs/runtime": "^2.1.0"
  }
}

其他

2020-08-18T21:25:03.000+08:00 日期怎么转换阿

问题是什么

问题的具体描述,尽量详细

环境

  • 系统: MAC 10.14.x
  • 浏览器:Chrome 7.4.x
  • 版本:2.0.0
  • 用到的插件: template, rollup-plugin-templatejs
  • 其他信息

在线例子

如果有请提供在线例子

其他

其他信息

注释问题

html注释会在dom结构显示,可以不显示吗?还有其他注释方式?
比如bdtmpl <%* *%>

请问兼容ie吗?

问题是什么

问题的具体描述,尽量详细

环境

  • 系统: MAC 10.14.x
  • 浏览器:Chrome 7.4.x
  • 版本:2.0.0
  • 用到的插件: template, rollup-plugin-templatejs
  • 其他信息

在线例子

如果有请提供在线例子

其他

其他信息

压缩配置有问题

目前压缩功能只是去掉生成代码中的空白字符,没有考虑到特殊情况,如html代码中标签含有属性、class、id标志,建议优化压缩功能的正则。个人想到以下可删除空白情况:

  • 每行起始和结尾的空格
  • 标签之间空格,但保留IE条件注释前后的换行
  • 注释,保留IE条件注释
  • href="javascript:后的空白

如何使用子模版?

目前还不支持子模板,但因为输出的地方是js表达式,是可以模拟子模版的

举一个例子,有一个新闻列表组件,这里涉及两个tmpl,newlist.tmpl, new.tmpl

new.tmpl

<%=title%> 
<%=date%>
<%=desc%>

newlist.tmpl

<%list.forEach(function (new) {%>
    <%:=newTpl(list)%>
<%});%>

脚本部分这么做

var data = {
    list: [
        {title: '1'},
        {title: '2'},
        {title: '3'},
    ]
}

newListTpl({list: data.list, newTpl: newTpl})

具体例子可以看这里:https://github.com/yanhaijing/template.js/blob/master/demo/child-template.html

template-loader在webpack5下如何配置

template-loader在webpack5下如何配置

[webpack-cli] Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.

  • configuration.module.rules[2] has an unknown property 'query'. These properties are valid:
    object { assert?, compiler?, dependency?, descriptionData?, enforce?, exclude?, generator?, include?, issuer?, issuerLayer?, layer?, loader?, mimetype?, oneOf?, options?, parser?, realResource?, resolve?, resource?, resourceFragment?, resourceQuery?, rules?, scheme?, sideEffects?, test?, type?, use? }
    -> A rule description with conditions and effects for modules.

这个轮子好学习,更简单的扩展进去吧

更简单的 扩展进去吧

(function(window){
    temp = function(str,obj){
        return str.replace(/\$\w+\$/gi, function(matchs) {
            var returns = obj[matchs.replace(/\$/g, "")];
            return typeof returns === "undefined" ? "" : returns;
        });
    }
    window.temp = temp
})(window);

调用:

temp('<ul><li data-id="$id$"> <span class="icon"></span> <span class="con">$name$ <span> (0) </span> </span> </li><ul></ul></ul>',{
    id:"jslite",
    name:"jslite.io"
})

请问这个数据为什么渲染不进去呢?

问题是什么

模板未渲染数据到html

环境

  • 系统: win10

  • 浏览器:版本 84.0.4147.89(正式版本) (64 位)

  • 版本:v1

  • 用到的插件: template.js

  • 其他信息

在线例子

<script id="tpl" type="text/html">

单元 : <%data[0].device_peril%>

上报人员 :

维保内容 :

位置 :

处理状态 :

上报时间 :

处理时间 :

执行人 :

</script> let data = [ { device_peril:'检修0', peril_level:'一级', peril_description:'一期化学除盐', peril_area:'隐患地点', discover_time:'2020-8-27 15:44:34', rectify_person:'周宁', plan_rectify_time: '2020-8-28 15:48:16', check_time:'2020-8-27 15:49:01' }] var html = template(document.getElementById('tpl').innerHTML,{device_peril:'1111'}); document.getElementById('wp').innerHTML = html;

其他

其他信息

在react中如何使用

因为项目涉及到使用百度鹰眼项目,其中官方鹰眼项目使用到baidutemplate模板,现整合到react项目中改如何使用? thx

else怎么用呢

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>基本用例</title>
    <!-- <script src="jquery-1.11.0.min.js"></script> -->
    <script src="template.js"></script>
    <style>
        table {
            border-collapse: collapse;
        }

        td {
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <div id="type"></div>
    <script id="tp2" type="text/html">
        <table>
            <tr>
                <td>字母</td>
                <td>类型</td>
            </tr>
            <%for (var i = 0; i < arr.length; i++) {%>
                <tr>
                    
                    <td>
                        <%=arr[i].zm%>
                    </td>
                    <%if (arr[i].type==1) {%>
                        <td>
                            11111
                                <%=typeFormat(arr[i].type)%>
                        </td>
                    <%else if (arr[i].type==3) %>
                        <td>
                                3333
                                    <%=typeFormat(arr[i].type)%>
                            </td>
                    <%}%>
                    
                </tr>
                <%}%>
        </table>
    </script>

    <script>
        template.registerFunction('typeFormat', function (param) {
            var str = ''
            if (param == 1) {
                str = '哇1'
            } else if (param == 2) {
                str = '哇2'
            } else {
                str = '哇3'
            }
            return str
        })
        var arr = [{
                'zm': 'a',
                "type": 1
            },
            {
                'zm': 'b',
                "type": 2
            },
            {
                'zm': 'c',
                "type": 1
            },
            {
                'zm': 'd',
                "type": 3
            }
        ];
        document.getElementById('type').innerHTML = template(document.getElementById('tp2').innerHTML, { typee: arr });
        template.unregisterFunction('typeFormat')
    </script>
</body>

</html>

想问下else的正确用法

请教compiler函数的返回函数为什么被定义成自执行函数

海镜你好,不是很明白compiler函数的返回函数被定义成自执行函数的用意,template.js第192行,类似以下代码:

var x = new  Function("_str", "(function(_str){console.log(_str)})(_str)"); x("str");

实际上new Function创建函数,参数已经传递给函数体,

var y = new  Function("_str", "console.log(_str)"); y("str");

不是很确定定义成自执行函数的作用和意图,能否烦请解惑一下,谢谢

如何添加多个标签属性

<body>
  <script type="text/html" id=tpl>
      <div data-a=<%= 3>4?'a':'' %> class=<%= 3>4?'active':'' %>>gogogo</div>
  </script>
  <div class="wp"></div>
  
  <script>
    var tpl = document.getElementById('tpl').innerHTML;
    var html = template(tpl, {})
    console.log(html)
    document.getElementsByClassName('wp')[0].innerHTML = html
  </script>
</body>

渲染的结果:

console.log:

"       <div data-a= class=>gogogo</div>     "

html:

<div class="wp">       <div data-a="class=">gogogo</div>   </div>

date-a 和 class 重叠了

jsbin链接: https://jsbin.com/docakehaxo/edit?html,console,output

有没有类似于vue的格式化功能?

找template,一般情况下,最常用的就三个功能,for循环遍历,if判断,和格式化,格式化,就是管道(可能用词不当),举个栗子,判断后端给的type是1,2,3,1显示为yes,2显示为no,3显示为未知,类似于这种,没有在文档里找到,能提示一下么?谢谢

是否考虑类似 v-if、v-for 的写法?

是否考虑类似 v-if、v-for 的写法?

现在这种写法怎么说呢,对于格式化代码不太友好吧,而且写完看起来会有点乱乱的

主要是 if 内的 html 格式化代码后会和 if 逻辑所在的标签同一层级,看不出来层级结构。。。

比如:

<#if(判断条件A) {#>
    <div>111</div>
<#} else if (判断条件B) {#>
    <#if (判断条件C) {#>
        <div>222</div>
    <#}#>
    <#if (判断条件D) {#>
        <div>333</div>
    <#}#>
<#}#>

当我按了格式化以后就会变成

<#if(判断条件A) {#>
<div>111</div>
<#} else if (判断条件B) {#>
<#if (判断条件C) {#>
<div>222</div>
<#}#>
<#if (判断条件D) {#>
<div>333</div>
<#}#>
<#}#>

如果 if 里头的代码再多一些的话,理解代码就会非常困难。。。。
而如果是在标签属性上加 if else的话,那么只要收起这个标签就能很清洗的了解逻辑了。。。

从模板的角度考虑的话,v-show 这种控制 css 的不需要实现,v-if + v-for 就能解决好多东西了

function template(tpl, data)

function template(tpl, data)点击分页再次调用这个方法, tpl是undefined这个应该如何处理?

fis预编译无法使用registerFunction?

使用registerFunction之后,在fis项目里面,通过__inline方式获取tpl,然后执行tpl({})的时候提示通过registerFunction的方式注册的方法未定义。不知道这种方式下怎么使用。求助,谢谢!

tmpl文件里的img src路径,fis在编译时不会识别处理?

tmpl文件里的img src路径,fis在编译时不会识别处理?
比如img src="/modules/forum/pages/img/folder_old.gif" ,如果写在html页面,fis编译后会输出
img src="/static/forum/pages/img/folder_old.gif"

但是如果写在*.tmpl文件里了,fis编译时,不会识别和处理该img。

亲,请问如何让fis处理tmpl里的img src路径?

期待回复,谢谢!

自带rem?

请问是自带rem吗?怎么我的字会根据屏幕大小跟着变,但是我看盒子里的数字却没有变。。。
image
image

使用问题

问题是什么

不能动态给标签追加各种属性吗?在哪都没找到相关问题。

环境

  • 系统: MAC 10.14.x
  • 浏览器:Chrome 7.4.x
  • 版本:2.0.0
  • 用到的插件: template, rollup-plugin-templatejs
  • 其他信息

在线例子

如果有请提供在线例子

其他

其他信息

A little advice.

如果能将demo push成gh-pages,就可以直接点开看效果了。

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.