Velocity. js-JS template engine from Taobao

Source: Internet
Author: User

Note:

Velocityjs in npm contains the name from the original velocity. changed js to velocityjs and felt require ("velocity. js ") is not easy to understand, so the name is changed. Versions later than 0.3.0 are all updated under velocityjs.

View the latest version

 
 
  1. $ npm info velocityjs version 

Velocity. js is the javascript Implementation of the velocity template syntax. Velocity is a Java-based template engine that is widely used in various subsidiaries of Alibaba Group. The Velocity template is applicable to scenarios where many templates are used. It supports complex logical operations, including basic data types, variable assignment, and functions. Velocity. js supports Node. js and the browser environment.

Latest Version: https://github.com/shepherdwind/velocity.js/zipball/master

Features
  • Support for client and server

  • The syntax is logically rich and forms a micro-language.

  • Separation of syntax analysis and template Rendering

  • Fully supports the velocity syntax.

  • The browser supports mutual reference between templates based on the loading mechanism of the kissy module.

  • Three Helper, user-friendly data simulation solution

  • Vim Syntax

Install

Via npm:

 
 
 
  1. $ npm install velocityjs 
Broswer Support

Compatible with other browsers such as ie6 + and chrome, test case

Click here to experience the web-side velocity Syntax Parsing process. Note: Using ACE as the Code Editor only supports advanced browser access.

RuncakeCommand to package the velocity. js browser script:

 
 
 
  1. $ make parse  

Coffeejs needs to be installed under the cli. Currently, the packaging is used by kissy. Some common ecma5 functions required by velocity. js, suchforeach, some, isArrayIn the node environment, it is a built-in function, and the web-side content is handed over to the existing class library. You need to provide a set of cross-browser APIs, such as kissy packaging:

 
 
 
  1. //api map  
  2. var utils = {  
  3.   forEach : S.each,  
  4.   some    : S.some,  
  5.   mixin   : S.mix,  
  6.   guid    : S.guid,  
  7.   isArray : S.isArray,  
  8.   indexOf : S.indexOf,  
  9.   keys    : S.keys,  
  10.   now     : S.now  
  11. };  

Velocity syntax has a high fault tolerance capability, similar to html structure parsing, and complex syntax rules, so the performance of the syntax interpreter may be slow,velocity.jsThe syntax structure analysis operation and syntax execution are independent. In the first step, the syntax structure analysis returns an array (syntax tree) that describes the velocity syntax. The syntax execution uses the data and syntax tree, calculates the final result of the template.

After the build is executed, two files are obtained, which arebuild/velocity/Underindex.jsAndparse.js, The two are independent of each other,parse.jsThe syntax analysis process can be completed locally by executing the following command:

Syntax analysis and templates are separated to facilitate local compilation of the syntax tree and reduce js operations on the web end. The idea of locally compiling templates is derived from the xtemplate of KISSY.

Although the syntax interpreter can be executed on a browser, it is not recommended to use it.

 
 
 
  1. # Using the velocity command line tool for packaging
  2. Veloctiy -- build *. vm
  3. Veloctiy-B *. vm

Source codetest/web/Part of the Directory js is obtained after offline compilation. You can directly access it here.

Public APInode_module
 
 
  1. Var Velocity = require ('../src/velocity ');
  2.  
  3. // 1. parse directly
  4. Velocity. render ('string of velocity ', context );
  5.  
  6. // 2. Use Parser and Compile
  7. Var Parser = Velocity. Parser;
  8. Var Compile = Velocity. Compile;
  9.  
  10. Var asts = Parser. parse ('string of velocity ');
  11. (New Compile (asts). render (context );
Context

contextIs an object. It can be null and is being executed.$foo.barThe access path iscontext.foo.bar,contextCan be a function, consistent with the definition in vm.

On Broswer

1. Use the offline packaging solution:

 
 
 
  1. KISSY.use('velocity/index, web/directives', function(S, Velocity, asts){  
  2.   var compile = new Velocity(asts);  
  3.   S.all('body').html(compile.render());  
  4. });  

2. Use online Compilation:

 
 
 
  1. KISSY.use('velocity/index, velocity/parse', function(S, Velocity, Parser){  
  2.   var html = (S.all('#tpl').html());  
  3.   var asts = Parser.parse(html);  
  4.   var compile = new Velocity(asts);  
  5.   console.log(compile.render());  
  6. });  

The difference between the two lies in the asts acquisition. The first method is to take asts directly, and the second method is to execute the syntax analysis process first.

Syntax

For more information about the syntax, see the velocity user guide.

Directives

Directives supportset,foreach,if|else|elseif,macro,parse,break. Not supported,stop,evaluate,define. These syntaxes are relatively biased and are of little use and are not implemented yet. WhereparseOn the web end, to use the kissy module loader for loading, you must first compile and package it offline, for example.

Macro

Macros are classified into system macros, suchparse, include, And user-defined macros, through#macroDefined in vm. In addition, you can use custom js functions to replace them with those defined in vm. System macros and custom macros are not differentiated.#parseAnd#includeYou can use a custom function to execute. For details, see issue #3.

Foreach

Foreach traverses objects in velocity, which is different from js. in java, an object is a map and needs to be passed throughkeysetTo obtain the key in the map. The foreach loop is equivalent to the js for in loop, which is a bit weird. In a foreach, there is$foreachCan be used, this variable scope is the current loop range.

 
 
  1. # Foreach ($ num in [1 .. 5])
  2. Index => $ foreach. index
  3. Count => $ foreach. count
  4. # If (! $ Foreach. hasNext) end # end
  5. # End
  6. Result:
  7. Index => 0
  8. Count => 1
  9.  
  10. Index => 1
  11. Count => 2
  12. ...
  13. Index => 4
  14. Count => 5
  15. End
String

In velocity, the value of the string is similar to that of php. The variable in the double quotation mark string will be replaced with the value corresponding to the variable, and the single quotation mark is returned as is. We recommend that you use single quotation marks as much as possible, which provides better performance. In addition, variables in double quotation marks are replaced by regular expressions instead of calling the syntax analyzer again. They only support simple replacement by reference, such"$varname1 $foo.bar","$foo.bar[1] $foo.bar()"None. If you need to fully support string double quotes, you need to call the syntax analyzer repeatedly. Considering the performance, the basic reference is enough. The vm itself supports powerful variable assignment. You can assign values first and place the values in the string, or use addition to concatenate strings.

A large number of double quotation marks may be used in java, Because java objects cannot automatically convert the type and double quotation marks are used for type conversion. On the web side, js does not need this.

Velocity
 
 
  1. Usage: velocity [options] [file ...]  
  2.  
  3. Options:  
  4.  
  5.   -h, --help         output usage information  
  6.   -V, --version      output the version number  
  7.   -b, --build        build .vm file to js ast module of kissy  
  8.  
  9. Example:  
  10.  
  11.   # parse vm file  
  12.   $ velocity a.vm   
  13.  
  14.   # parse vm file with json data  
  15.   $ velocity a.vm  a.json  
  16.  
  17.   # build asts module of kissy  
  18.   $ velocity *.vm  
Helper

Helper provides some additional functions to solve vm data simulation problems.

  • structureObtain the structure of all variables in the vm:$foo.bar=>foo: {bar: 'string'}
  • backstepVm reverse push: calculates the data structure and content based on the velocity file and the parsed result.
  • jsonifyConvert the vm to a json structure and remove the html tags, for example:

Jsonify Document issue #11

 
 
  1. hello world $foo.name.  
  2. =>  
  3. {foo: { name: $foo.name }}  
License

(The MIT License)

Copyright (c) 2012-2013 Eward Songeward.song@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'soft'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or duplicate copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be encoded in all copies or substantial portions of the Software.

The software is provided 'as IS ', without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particle purpose and noninfringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.

From: https://github.com/shepherdwind/velocity.js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.