Permalink
Browse files

Initial commit

  • Loading branch information...
1 parent 6e881e6 commit aecb675c048468eccca3e9f71d06b406e39d34cc Pierre Matri committed May 19, 2012
Showing with 3,383 additions and 2 deletions.
  1. +7 −0 LICENSE
  2. +4 −0 Makefile
  3. +112 −2 README.md
  4. +7 −0 index.js
  5. +1 −0 kiwi
  6. +253 −0 lib/compiler.js
  7. +69 −0 lib/filter.js
  8. +456 −0 lib/filters/base.js
  9. +52 −0 lib/filters/datetime.js
  10. +36 −0 lib/kiwi.js
  11. +67 −0 lib/tags/block.js
  12. +58 −0 lib/tags/comment.js
  13. +139 −0 lib/tags/each.js
  14. +97 −0 lib/tags/extend.js
  15. +139 −0 lib/tags/if.js
  16. +90 −0 lib/tags/include.js
  17. +152 −0 lib/tags/print.js
  18. +64 −0 lib/tags/tmpl.js
  19. +74 −0 lib/tags/verbatim.js
  20. +295 −0 lib/template.js
  21. +386 −0 lib/token.js
  22. +212 −0 lib/utils.js
  23. +25 −0 package.json
  24. BIN test/cases/.DS_Store
  25. 0 test/cases/empty.html
  26. 0 test/cases/empty.kiwi
  27. +2 −0 test/cases/tag.block.html
  28. +2 −0 test/cases/tag.block.kiwi
  29. +1 −0 test/cases/tag.comment.html
  30. +2 −0 test/cases/tag.comment.kiwi
  31. +13 −0 test/cases/tag.each.html
  32. +13 −0 test/cases/tag.each.kiwi
  33. 0 test/cases/tag.extend.html
  34. +83 −0 test/cases/tag.extend.js
  35. 0 test/cases/tag.extend.kiwi
  36. +9 −0 test/cases/tag.if.html
  37. +13 −0 test/cases/tag.if.kiwi
  38. +2 −0 test/cases/tag.include.html
  39. +2 −0 test/cases/tag.include.kiwi
  40. +69 −0 test/cases/tag.print.html
  41. +32 −0 test/cases/tag.print.js
  42. +69 −0 test/cases/tag.print.kiwi
  43. +1 −0 test/cases/tag.tmpl.html
  44. +1 −0 test/cases/tag.tmpl.kiwi
  45. +4 −0 test/cases/tag.verbatim.html
  46. +4 −0 test/cases/tag.verbatim.kiwi
  47. +2 −0 test/fixtures/dynamic.kiwi
  48. +1 −0 test/fixtures/hello.kiwi
  49. +2 −0 test/fixtures/intermediate.kiwi
  50. +2 −0 test/fixtures/leaf.kiwi
  51. +1 −0 test/fixtures/root.kiwi
  52. +3 −0 test/mocha.opts
  53. +84 −0 test/run.js
  54. +171 −0 test/template.js
View
@@ -0,0 +1,7 @@
+Copyright ©2012 Pierre Matri <pierre.matri@coolony.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 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 included 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 PARTICULAR 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.
View
@@ -0,0 +1,4 @@
+test:
+ @./node_modules/.bin/mocha
+
+.PHONY: test
View
114 README.md
@@ -1,2 +1,112 @@
-kiwi
-====
+# Kiwi
+
+## What is this?
+
+Kiwi is a cool JavaScript template engine lovingly built from the ground up for Node.js with performance, extensibility, modularity and security in mind. It is compatible with most of [jQuery templates](http://api.jquery.com/category/plugins/templates/) syntax, and adds lots of features to it. This means Kiwi is:
+
+* **Fast**. Insanely fast.
+* **Completely asynchronous**. You have the absolute guarantee that not a single blocking call will be done after Kiwi has been initialized.
+* **Easily extensible**. Three short lines of code are enough to create a new tag.
+* **Incredibly powerful**, even for advanced features. Want dynamic template inheritance? Access individual block contents? Done!
+* **Easy to set up**. One line of code and you can get started on [Express](http://expressjs.com) 3.x. You can even directly use your existing jQuery or [jqTpl](https://github.com/kof/node-jqtpl) templates.
+* **Robust**. Kiwi is carefully tested before any change is pushed to the repository.
+* **Full-featured**. Lots of filters are available, and it can't be easier to add your own if you want.
+* **Secure**. All output is escaped by default.
+* **Clean**. Kiwi won't mess with your prototypes, and won't extend any of the built-in JavaScript objects
+
+## Syntax
+
+```html
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>${title}</title>
+ </head>
+ <body>
+ <p>
+ {{if name}}
+ Hello, ${name|capitalize}!
+ {{else}}
+ Hello, dear unknown!
+ {{/if}}
+ </p>
+ </body>
+</html>
+```
+
+## Installation
+
+### Latest release
+
+```bash
+npm install kiwi
+```
+
+### Development version (may not be suited for production [yet])
+
+```bash
+npm install https://github.com/coolony/kiwi/tarball/master
+```
+
+## Usage
+
+```javascript
+var kiwi = require('kiwi');
+
+var template = '<p>Hello, ${name}!</p>';
+new kiwi.Template(template).render({name: "Kiwi"}, function onRendered(err, rendered) {
+ console.log('Rendered template is: ' + rendered);
+});
+```
+
+## Available filters
+
+* escape
+* capitalize
+* upper
+* lower
+* json
+* add
+* subtract
+* mul
+* div
+* cut
+* addslashes
+* stripslashes
+* first
+* last
+* length
+* reverse
+* join
+* urlencode
+* urldecode
+* replace
+* date
+* relativedate
+* timeago
+
+## Performance tips
+
+* **Use cache in production**
+* **Use strict mode**
+You can disable strict mode in order to make Kiwi comply with jQuery template / jqTpl behaviour. However, this will result in using a bunch of `try…catch` blocks in the compiled templates, which will definitely lower Kiwi's performance.
+Strict mode is enabled by default.
+* **Avoid using `tmpl`**
+In order to avoid memory leaks when using heavily dynamic templates in `tmpl`, this tag uses `CappedCache` by default, isolated from the main cache. As a result, if your nested templates are heavily dynamic, a new complete compiler stack is likely to be started each time a `tmpl` tag is met.
+You may choose to use a standard cache instead, but be aware that this could easily lead to huge memory leaks if your nested templates are heavily dynamic.
+It is included for compatibility with jQuery templates / jqTpl, but you should probably not use it at all.
+* **Consider disabling `eachLoopCounters`**
+Kiwi adds counters to `each` loop, which allows you, for example, to access the current iteration count with `_eachLoop.counter`. If you don't need this functionality, disabling it will slightly increase Kiwi's performance when using `each` loops.
+
+
+## License
+
+**Kiwi is released under an MIT license**
+
+Copyright ©2012 Pierre Matri <pierre.matri@coolony.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 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 included 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 PARTICULAR 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.
View
@@ -0,0 +1,7 @@
+/*!
+ * Coolony's Kiwi
+ * Copyright ©2012 Pierre Matri <pierre.matri@coolony.com>
+ * MIT Licensed
+ */
+
+module.exports = require('./lib/kiwi')
View
1 kiwi
View
@@ -0,0 +1,253 @@
+/*!
+ * Coolony's Kiwi
+ * Copyright ©2012 Pierre Matri <pierre.matri@coolony.com>
+ * MIT Licensed
+ */
+
+
+/**
+ * Module dependencies
+ */
+
+var token = require('./token');
+var utils = require('./utils');
+
+
+/**
+ * Constants
+ */
+
+var TAG_OPENING_DELIMITER = '{{';
+var TAG_CLOSING_DELIMITER = '}}';
+var TAG_OPENING_DELIMITER_LENGTH = TAG_OPENING_DELIMITER.length;
+var TAG_NAME_MATCH = /^(\/)?\s*([^\s\}\(]*)/i;
+
+
+/**
+ * Initialize `Compiler` with the given `Template`, from the given `source`,
+ * with `options`.
+ *
+ * @param {String} source
+ * @api private
+ */
+
+var Compiler = module.exports = function(template) {
+ this.template = template;
+ this.source = template.template;
+ this.options = template.options;
+ this.__compilationEnd = [];
+}
+
+
+/**
+ * Compile template to a native JS function, and invoke
+ * `callback(err, compiled)`.
+ *
+ * @param {Function} callback
+ * @api private
+ */
+
+Compiler.prototype.compile = function(callback) {
+ var _this = this;
+
+ // Callback for utils.applyAll
+ function onProcessed(err, processed) {
+ if(err) return callback(err);
+ _this._tokenize(processed, onTokenized);
+ }
+
+ // Callback for Compiler#_tokenize
+ function onTokenized(err, tokenized) {
+ if(err) return callback(err);
+ tokenized.compile(_this, onCompiled);
+ }
+
+ // Callback for Compiler#_compileTokens
+ function onCompiled(err, compiled) {
+ if(err) return callback(err);
+ //console.log(compiled);
+ callback(null,
+ new Function("__template",
+ "__tools",
+ "_",
+ "__data",
+ "__helpers",
+ "__callback",
+ compiled)
+ );
+ }
+
+ // Apply tag before processors
+ utils.applyAll(this.source, token.tagBeforeProcessors, [this], onProcessed);
+}
+
+
+/**
+ * Tokenize template, and invoke `callback(err, tokenized)`.
+ *
+ * @param {Function} callback
+ * @api private
+ */
+
+Compiler.prototype._tokenize = function(source, callback) {
+ var workingSource = source;
+ var currentToken = new token.RootToken();
+ var rootToken = currentToken;
+ var inToken = false;
+ var currentPart;
+
+ // Lookup templates in document, and build parse tree
+ while(true) {
+ var nextInflexion = workingSource.indexOf(inToken ?
+ TAG_CLOSING_DELIMITER :
+ TAG_OPENING_DELIMITER
+ );
+
+ if(nextInflexion == -1) {
+ this._pushLiteralToken(rootToken, currentToken, workingSource);
+ break;
+ } else {
+ if(inToken) nextInflexion = nextInflexion + TAG_OPENING_DELIMITER_LENGTH;
+ currentPart = workingSource.slice(0, nextInflexion);
+ workingSource = workingSource.slice(nextInflexion);
+
+ if(!inToken) {
+ this._pushLiteralToken(rootToken, currentToken, currentPart);
+ } else {
+ currentPart = currentPart.slice(2, -2).trim();
+ try {
+ currentToken = this._pushToken(rootToken, currentToken, currentPart);
+ } catch(err) {
+ return callback(err);
+ }
+ }
+
+ inToken = !inToken;
+ }
+ }
+
+ // Ensure we are at root level
+ if(rootToken !== currentToken) {
+ return callback(new Error( 'Tokenization error: unexpected end of file, '
+ + 'expedted `'
+ + currentToken.tag.tagName
+ + '`.')
+ );
+ }
+
+ callback(null, rootToken);
+}
+
+
+/**
+ * Create `LiteralToken` with `literal`, and append it to `parent`.
+ *
+ * @param {BaseToken} parent
+ * @param {String} literal
+ * @api private
+ */
+
+Compiler.prototype._pushLiteralToken = function(root, parent, literal) {
+ if(!literal.length) return;
+ parent.children.push(new token.LiteralToken(literal, root));
+}
+
+
+/**
+ * Create `BaseToken` from tag `tag`, and append it to `current`.
+ * Return the new working token.
+ *
+ * @param {BaseToken} current
+ * @param {String} tag
+ * @return {BaseToken} New working token.
+ * @api private
+ */
+
+Compiler.prototype._pushToken = function(root, current, tag) {
+ var match = tag.match(TAG_NAME_MATCH);
+ var tagName = match[2];
+ var openingTag = match[1] !== '/';
+ var tagType = current.lookupTag(tagName);
+
+ // Check whether we know this tag
+ if(!tagType) {
+ throw new Error('Tokenization error: Unknown tag `' + tagName + '`.');
+ }
+
+ // Handle intermediate tags
+ if(tagType.isIntermediate) {
+
+ // If we already are in an intermediate tag, close it
+ if(current.tagType.isIntermediate) current = current.parent;
+
+ // Push the tag to the stack
+ var newToken = new token.IntermediateToken(tag,
+ tagType,
+ root,
+ current,
+ [],
+ this.options);
+ current.intermediate.push(newToken);
+ return newToken;
+
+ }
+
+ // Handle block tags
+ else if(tagType.isBlock) {
+
+ // Handle opening tags
+ if(openingTag) {
+ var newToken = new token.BlockToken(tag,
+ tagType,
+ root,
+ current,
+ [],
+ this.options);
+
+ current.children.push(newToken);
+ return newToken;
+
+ // Handle closing tags
+ } else {
+ if(!current.parent) {
+ throw new Error( 'Tokenization error: unexpected `'
+ + tagName
+ + '` tag at root level.'
+ );
+ }
+
+ if(current.tagType.isIntermediate) {
+ current = current.parent;
+ }
+
+ if(current.tagType.tagName !== tagName) {
+ throw new Error( 'Tokenization error: unexpected `'
+ + tagName
+ + '` tag, expected `'
+ + current.tag.tagName
+ + '`.'
+ );
+ }
+ return current.parent;
+ }
+ }
+
+ // Handle leaf tags
+ else {
+
+ // Ensure we don't have a closing tag
+ if(!openingTag) {
+ throw new Error( 'Tokenization error: `'
+ + tagName
+ + '` is not a block tag.'
+ );
+ }
+ var newToken = new token.LeafToken(tag,
+ tagType,
+ root,
+ current,
+ this.options);
+ current.children.push(newToken);
+ return current;
+ }
+}
Oops, something went wrong.

0 comments on commit aecb675

Please sign in to comment.