• Stars
    star
    257
  • Rank 158,728 (Top 4 %)
  • Language
    JavaScript
  • Created over 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Light weight but powerful template engine for JavaScript

sodajs

An amazing directive template engine for JavaScript.

中文说明

Fetures

  • super tiny size (4kb gzipped)
  • dom directives support
  • good compatibility (IE8 +, node)
  • prevents XSS holes out of your template file
  • high-performance DOM parser
  • directive Api compatibile with AngularJS
  • custom directive and prefix

Install

npm

npm install --save sodajs 

CDN

Usage

Difference between soda & soda.node

version soda soda.node
Mordern Browsers
Mobile Browsers
ie ≥8 ≥9
node
DOM Parsor Native Self

warning: ie 8 needs es5-shim or es5-sham and console-polyfill

check ie 8 test below

Browser

  • script tag
<script src="https://unpkg.com/[email protected]/dist/soda.min.js"></script>
  • with webpack
   import soda from "sodajs"

Node

let soda = require('sodajs/node');

or use dist version for older node

let soda = require('sodajs/dist/soda.node')

API

Output

plain

var tpl = '<div>{{name}}</div>';

document.body.innerHTML = soda(tpl,{ name : 'soda' })

plain example

safe propery chain output

var data = {
    name: 'soda',
    info: {
        version: '2.0'
    }
}

soda("{{info.version}}", data);  
// result => "2.0"


soda("{{info.foo.foo1}}", data)
// result => ""      without errors

soda("{{info['name']}}", data)
// result => "2.0"

expression

var data = {}

soda("{{1 + 2}}", data);  
// result => 2


soda("{{true ? 'soda' : 'foo'}}", data)
// result => "soda"      

soda("{{1 < 3 && 'soda'}}", data)
// result => "soda"

expression example

complex expression

 var data = {
      list: [
         {list: [{'title': '<>aa</h1>'}, {'title': 'bb'}], name: 0, show: 1},
         {list: [{'title': 0 }, {'title': 'bb'}], name: 'b'}
        ]
       
 };

 soda('{{list[list[0].show === 1 ? list[0].name : 1].list[0].title}}', data)
 // result => '<>aa</h1>'

Directives

if

var data = { name : 'soda',show: true };
soda(` <div soda-if="show">Hello, {{name}}</div>
       <div soda-if="!show">I\'m hidden!</div>`,
       data
    )
// result => <div>Hello, soda</div>

if example

repeat

soda-repeat="item in array"

soda-repeat="item in object"

soda-repeat="item in array by index"

soda-repeat="item in object by key"

soda-repeat="(index, value) in array"

soda-repeat="(key, value) in object"

default index or key is $index

var tpl = '\
<ul>\
    <li soda-repeat="item in list" soda-if="item.show">\
        {{item.name}}\
        {{$index}}\
    </li>\
</ul>'

var data = {
    list: [
        {name: "Hello" ,show: true},
        {name: "sodajs" ,show: true},
        {name: "AlloyTeam"}
    ]
};

document.body.innerHTML =  soda(tpl, data);

repeat example

filter

soda.filter(String filterName, Function func(input, args...)) {{input|filte1:args1:args2...|filter2:args...}}

example:

soda.filter('shortTitle', function(input, length){
    return (input || '').substr(0, length);
});

var tpl = '\
<ul soda-repeat="item in list">\
    <li class="title">\
        {{item.title|shortTitle:10}}\
    </li>\
</ul>'


document.body.innerHTML = soda(tpl,{ list : [
    {title:'short'},
    {title:'i am too long!'}
] })

filter example

html

output origin html as innerHTML

var tpl = '<div soda-html="html"></div>'
document.body.innerHTML = soda(tpl,{ html : '<span style="color:red;">test soda-html</span>' })

html example

replace

replace this node with html

var tpl = '<div soda-replace="html"></div>'
document.body.innerHTML = soda(tpl,{ html : '<span style="color:red;">test soda-html</span>' })

replace example

div will be replaced with given html

include

include template

soda-include="tmplateName:arg1:arg2:..." with soda.discribe, we can include sub templates

    var data = {
        name: "soda"
    };
    
	// define sub template named tmpl1
    soda.discribe('tmpl1', `<h1>{{name}}</h1>`);
    
	
	// use template tmpl1 by soda-include
    soda(`<span soda-include="tmpl1">1</span>`, data);
    // result => <h1>dorsy</h1>
    
	// set compile false not to compile sub template
	soda.discribe('tmpl1', `<h1>{{name}}</h1>`, {
		compile: false
	});
 
 	// show origin template
    soda(`<span soda-include="tmpl1">1</span>`, data);
    // result => <h1>{{name}}</h1>

    soda.discribe('tmpl2', function(path){
        return `<h1>{{name}}_${path}</h1>`;
    });

    soda(`<span soda-include="list3:sub{{'path' + 1}}">1</span>`, data);
    //  result =>  <h1>soda_subpath1</h1>
    

    // In node env
    soda.discribe('tmplNode', function(path){
        return fs.readFileSync(path, 'utf-8');
    });

    soda(`<span soda-include="tmplNode:view.html">1</span>`, data);
    //  result =>  view.html Tmplate

Others

soda-class

soda-class="currItem === 'list1' ? 'active' : ''"

soda-src

soda-src="hello{{index}}.png"

soda-style

soda-style="style"

data example:

var data = { style : { width : '100px', height : '100px' } };

soda-*

soda-rx="{{rx}}%"

soda-checked="{{false}}"

if the value is false or "", the attribute will be removed

Custom

soda.prefix

change prefix as you like, the default prefix is "soda-"

soda.prefix('v:')

var tpl = '\
<ul>\
    <li v:repeat="item in list" v:if="item.show">\
        {{item.name}}\
    </li>\
</ul>'


var data = {
    list: [
        {name: "Hello" ,show: true},
        {name: "sodajs" ,show: true},
        {name: "AlloyTeam"}
    ]
};

document.body.innerHTML =  soda(tpl, data);

soda.directive

Custom your directive

es 2015

soda.directive('name',  {
    priority: 8,
	
	// how to compile el
    link({ scope, el, parseSodaExpression, expression,  getValue, compileNode, document }) {

    }
});
  • scope: current scope data
  • el: current node elment
  • expression: directive string value
  • getValue: get value from data
     getValue({a: {b: 1}}, "a.b");  // ===>   1
  • parseSodaExpression: parse soda expressions
    parseSodaExpression('{{1 + 2 + a}}', {a: 1}); // ===> 4
  • compileNode: compile new nodes
  • document: using document rather than window.document to run in node env;

example

soda.directive('mydirective', {
    priority: 8,

    link({ scope, el, parseSodaExpression, expression,  getValue, compileNode, document }) {
        var value = parseSodaExpression(expression);
        if(value){
            var textNode = document.createTextNode(value);
            el.appendChild(textNode);
        }
    }
}

soda(`
    <div soda-mydirective="add one tips: {{tips}}"></div>
`, {
    tips: 'tips'
});

// result  ==>   <div>add one tips: tips</div>

soda.setDocument

custom dom parsor for node running.

soda.node version default document dom parsor is nodeWindow.

var document = require('document');
var soda = require('soda');

soda.setDocument(document);

// ... run 

Contribute

Development

git clone

 git clone git://github.com/AlloyTeam/sodajs.git

install dependency

    npm install

then run npm start

    npm start

publish code to run test

    npm run build

Auto-Test

soda uses mocha to run test

test unit is in test dir.

    npm run test

online test result

Used projects

QQ Tribes(兴趣部落), QQ Group(群) and other projects

License

MIT

Copyright (c) 2015-present, AlloyTeam

More Repositories

1

Mars

腾讯移动 Web 前端知识库
9,612
star
2

AlloyFinger

Super tiny size multi-touch gestures library for the web.    You can touch this →
JavaScript
3,418
star
3

AlloyImage

基于HTML5的专业级图像处理开源引擎。An image processing lib based on html5.
JavaScript
3,018
star
4

PhyTouch

Smooth scrolling, rotation, pull to refresh, page transition and any motion for the web - 丝般顺滑的触摸运动方案
JavaScript
2,968
star
5

eslint-config-alloy

Progressive ESLint config for your React/Vue/TypeScript projects
JavaScript
2,641
star
6

AlloyLever

1kb js library contains development debugging, error monitoring and reporting, user problem localization features - 1KB代码搞定开发调试发布,错误监控上报,用户问题定位
JavaScript
1,382
star
7

curvejs

Made curve a dancer in HTML5 canvas - 魔幻线条
JavaScript
1,303
star
8

CodeGuide

Alloyteam代码规范
HTML
1,279
star
9

JX

JX(Javascript eXtension tools) 是腾讯AlloyTeam推出的模块化、非侵入式Web前端框架,适合构建和组织工业级大规模、高效率的 Web App
JavaScript
1,153
star
10

AlloyCrop

The best and tiny size mobile cropping component - 做最好且最小的移动裁剪组件
JavaScript
941
star
11

Rythem

a fiddler-like project using Qt
C++
888
star
12

alloyteam.github.com

腾讯 AlloyTeam 开源项目官网 - 我们的愿景: 成为业界卓越的Web团队!
JavaScript
849
star
13

alloy-worker

面向事务的高可用 Web Worker 通信框架
TypeScript
644
star
14

AlloyStick

AlloyStick 骨骼动画引擎 - 腾讯 AlloyTeam
JavaScript
437
star
15

Rosin

A tool for web developers debug mobile page with fiddler. http://alloyteam.github.io/Rosin/
C#
312
star
16

StreetFighter

街霸StreetFighter
JavaScript
305
star
17

webtop

HTML5 本地App开发引擎
C++
290
star
18

AlloyPhoto

JavaScript
277
star
19

gopng

GoPng - a HTML5 css sprite generator with cool feature.
273
star
20

tslint-config-alloy

AlloyTeam TSLint 规则
JavaScript
205
star
21

JXAnimate

基于CSS3的并行动画、声音引擎 - JX.Animate
CSS
195
star
22

AlloyTimer

AlloyTimer定时器 - 番茄工作法的时间管理应用
JavaScript
195
star
23

JMUI

移动Web开发UI组件库
JavaScript
178
star
24

AlloyViewer

H5图片查看器—Imageview component built with react
JavaScript
176
star
25

JM

面向Mobile的极致JavaScript库
JavaScript
141
star
26

AlloyDesigner

AlloyDesigner是一款致力于提高前端生产效率的浏览器内运行工具,AlloyDesigner + Chrome F12(Especially with WorkSpace) 打造前端新的开发和测试模式
138
star
27

omi-cli

Create website with no build configuration - 创建网站无需任何配置
JavaScript
125
star
28

AlloyPullRefresh

JavaScript
119
star
29

Spirit

腾讯移动Web整体解决方案
CSS
117
star
30

CodeTank

CodeTank(代码坦克)是全世界首款 Javascript 程序员的游戏, 由腾讯 AlloyTeam 用 HTML5、Javascript 等 Web 新技术来构建一个基于互联网的智能坦克机器人战斗仿真引擎
114
star
31

AlloyClip

A PC & Mobile Image Clip Kit based on AlloyImage
JavaScript
108
star
32

MLogger

一个浮在页面上的日志查看工具
JavaScript
100
star
33

Abstract.js

Abstract.js is a web framework for fast development
JavaScript
46
star
34

AlloyLint

apply eslint autofix but keep last author info in git blame。运行 eslint 的自动修复,但是保留最后修改人的信息
TypeScript
41
star
35

AlloyFlow

made workflow simple
JavaScript
38
star
36

AlloyTicker

The Master of Time          DEMO
JavaScript
25
star
37

netural

JavaScript前向神经网络(推理)和反向传播(训练)的实现
JavaScript
22
star