Skip to content

PaulGuo/Juicer

Folders and files

Name Name
Last commit message
Last commit date

Latest commit

 

History

228 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Juicer Chinese Document

Current latest version: 0.6.14

Juicer is an efficient and lightweight Javascript template engine. With Juicer, your code can realize the separation of data and view model (MVC). In addition, it can also run in the Node.js environment.

You can use and distribute it freely under the premise of abiding by MIT License. Juicer code is completely open source and hosted in Github If you find any bugs or some good suggestions in the process of using, welcome to Github Issue Submit on.

Origin of name

If we compare data to fresh and delicious fruit and templates to water, Juicer is a juicer that extracts the HTML code fragments we need from fruit and water.

Introduction of Juicer

 <script type="text/javascript" src="juicer-min.js></script>

*Usage

>Compile the template and render the result immediately according to the given data

 juicer(tpl, data);

>Only the compiled template will not be rendered temporarily. It will return a reusable compiled function

 var compiled_tpl = juicer(tpl);

>According to the given data, render the previously compiled template

 var compiled_tpl = juicer(tpl); var html = compiled_tpl.render(data);

>Register/unregister the user-defined function (object). There will be instances in the following ${variable}

 juicer.register('function_name', function); juicer.unregister('function_name');

>The syntax boundary character of the user-defined template is the default boundary character of Juicer. You can use this to solve the conflicts between Juicer template syntax and some back-end language template syntax

 juicer.set({ 'tag::operationOpen': '{@', 'tag::operationClose': '}', 'tag::interpolateOpen': '${', 'tag::interpolateClose': '}', 'tag::noneencodeOpen': '$${', 'tag::noneencodeClose': '}', 'tag::commentOpen': '{#', 'tag::commentClose': '}' });

Default parameter configuration

 { cache:          true [false], strip:          true [false], errorhandling:  true [false], detection:      true [false] }

The default configuration is the use method recommended by Juicer. If you really need to change these parameters during use, you can do this:

Change parameters one by one:

 juicer.set('strip',false); juicer.set('cache',false);

Batch parameter change:

 juicer.set({ 'strip': false, 'cache': false };

Juicer will cache the compiled template by default, so as to avoid the time spent repeatedly compiling the same template during multiple data rendering. If there is no special need, it is strongly recommended not to close the cache in the default parameters, which will invalidate Juicer cache and reduce performance

*Grammar

a. ${variable}

use ${} Output variable value, where _ Is a reference to a data source (such as ${_} , usually used when the data source is an array). Support user-defined functions (you can achieve many interesting functions through user-defined functions, such as ${data|links} You can directly assemble the data through the predefined user-defined function links <a href=".." alt=".." /> ).

 ${name} ${name|function} ${name|function, arg1, arg2}

Let's use an example to demonstrate the wonderful use of custom functions

 var json = { links: [ {href: ' http://juicer.name ', alt: 'Juicer'}, {href: ' http://benben.cc ', alt: 'Benben'}, {href: ' http://ued.taobao.com ', alt: 'Taobao UED'} ] }; var tpl = [ '{@each links as item}', '${item|links_build} <br />', '{@/each}' ].join(''); var links = function(data) { return '<a href="' + data.href + '" alt="' + data.alt + '" />'; };

juicer.register('links_build', links); // Register Custom Functions juicer(tpl, json);

After executing the above code, we will find that the result is as follows:

 &lt; a href=&quot; http://juicer.name&quot ;  alt=&quot; Juicer&quot; < br /> &lt; a href=&quot; http://benben.cc&quot ;  alt=&quot; Benben&quot; < br /> &lt; a href=&quot; http://ued.taobao.com&quot ;  alt=&quot; Taobao UED&quot; < br />

It can be seen that the result has been escaped. If we use $${item | links} above, we will get the expected result, which is the avoidance of escape mentioned below.

Escape/Avoid Escape

For safety reasons, ${variable} The content will be escaped before output. If you do not want the output result to be escaped, you can use $${Variable} To avoid this situation. For example:

 var json = { value: '&lt; strong&gt; juicer&lt;/ strong&gt;' }; var escape_tpl='${value}'; var unescape_tpl='$${value}'; juicer(escape_tpl, json); // Output '&lt; strong&gt; juicer&lt;/ strong&gt;' juicer(unescape_tpl, json); // Output '<strong>judge</strong>'

b. Loop through {@ each} {@/each}

If you need to loop through the array, you can use it like this each .

 {@each list as item} ${item.prop} {@/each}

It is also convenient to get the current index value during traversal

 {@each list as item, index} ${item.prop} ${index}//Current index {@/each}

c. Judge {@ if} {@else if} ... {@else} ... {@/if}

We also often encounter the time of logical judgment on data

 {@each list as item,index} {@if index===3} the index is 3, the value is ${item.prop} {@else if index === 4} the index is 4, the value is ${item.prop} {@else} the index is not 3, the value is ${item.prop} {@/if} {@/each}

d. Comment {# Comment content}

For the maintainability and readability of subsequent code, we can add comments in the template

 {# Here is the comment content}

e. Auxiliary cycle {@ each i in range (m, n)}

Auxiliary circulation is a grammar sugar carefully set for you by Juicer. Maybe you will need it under certain circumstances

 {@each i in range(5, 10)} ${i}; // Output 5; 6; 7; 8; 9; {@/each}

f. Sub template nesting {@ include tpl, data}

Sub template nesting allows you to organize your template code more flexibly. In addition to introducing the sub template specified in the data, you can also specify the string #id Use write in script Template code in the label

HTML code:

 <script type="text/juicer" id="subTpl"> I'm sub content, ${name} </script>

Javascript code:

 var tpl = 'Hi, {@include "#subTpl", subData}, End.'; juicer(tpl, { subData: { name: 'juicer' } }); //Output Hi, I'm sub content, judge, End //Or, the following code will have the same rendering result by importing data into the sub template: var tpl = 'Hi, {@include subTpl, subData}, End.'; juicer(tpl, { subTpl: "I'm sub content, ${name}", subData: { name: 'juicer' } });

*Run in Node.js environment

 Execute on the command line: npm install juicer In the code, it is introduced as follows: var juicer = require('juicer'); var html = juicer(tpl, data);

Use in the Express.js framework

In the Express 2. x series:

 npm install juicer var juicer = require('juicer'); app.set('view engine', 'html'); app.register('.html', { compile: function(str, options) { return juicer.compile(str, options).render; } });

In the Express 3. x series:

 npm install juicer var juicer = require('juicer'); var fs = require('fs'); app.set('view engine', 'html'); app.engine('html', function(path, options, fn){ fs.readFile(path, 'utf8', function(err, str){ if (err) return fn(err); str = juicer(str, options); fn(null, str); }); });

In the Express 4. x series:

 var juicerExpressAdapter = require('juicer-express-adapter'); app.set('view engine', 'html'); app.engine('html', juicerExpressAdapter);

Precompile the template file on the command line:

 npm install -g juicer juicer example.juicer.tmpl -f example.js // type `juicer` after install for more help. //After installing 'juicer' in global mode, enter 'juicer' at the command line to get more help information.

Set external cache storage for template engine:

 var juicer = require('juicer'); var LRUCache = require('lru-native'); var cache = new LRUCache({ maxElements: 1000 }); juicer.set('cachestore', cache);

*A complete example

 HTML code: <script id="tpl" type="text/template"> <ul> {@each list as it,index} <li>${it.name} (index: ${index})</li> {@/each} {@each blah as it} <li> num: ${it.num} <br /> {@if it.num==3} {@each it.inner as it2} ${it2.time} <br /> {@/each} {@/if} </li> {@/each} </ul> </script> Javascript code: var data = { list: [ {name:' guokai', show: true}, {name:' benben', show: false}, {name:' dierbaby', show: true} ], blah: [ {num: 1}, {num: 2}, {num: 3, inner:[ {'time': '15:00'}, {'time': '16:00'}, {'time': '17:00'}, {'time': '18:00'} ]}, {num: 4} ] }; var tpl = document.getElementById('tpl').innerHTML; var html = juicer(tpl, data);