Compare commits

..
95 Commits
Author SHA1 Message Date
harttle be17d7443c 1.9.7 2017-10-21 10:50:44 +08:00
Mehdi JafferyandJun Yang 118624ca7d Fix to make for tag iterate objects like Shopify liquid.
Ref: https://github.com/Shopify/liquid/wiki/Liquid-for-Designers#allowed-collection-types
2017-10-18 05:41:43 -05:00
harttle d08ad6dc97 fix: error.stack assertion in v8.5 2017-10-06 12:32:06 +08:00
harttle e22870f5d7 fix: broken unit test by UTC time parsing behaviour change 2017-10-06 12:16:03 +08:00
harttle bd6706cf4d update outdated 2017-10-05 08:32:32 +08:00
harttle b71928ffd4 refactor: format 2017-10-05 08:21:32 +08:00
harttle 6f69cd774d 1.9.6 2017-09-15 10:39:18 +08:00
harttle 1b662d374d update outdated dependencies 2017-09-15 10:38:54 +08:00
harttle 6dd6ed176c 1.9.5 2017-08-26 17:58:14 +08:00
harttle 21af8c4d7a fix read/write variable in parent's scope, fix #39 2017-08-26 17:57:43 +08:00
harttle 942a3224a1 1.9.4 2017-08-16 00:07:47 +08:00
harttle 11259fae62 fix stack matching 2017-08-16 00:04:31 +08:00
harttle 030037eedc cover all 2017-08-15 23:52:05 +08:00
harttle 6d59f34fc8 cover all 2017-08-14 22:43:49 +08:00
harttle 72597c52e5 cover all 2017-08-14 22:07:08 +08:00
harttle 7904f823a8 1.9.3 2017-08-04 11:28:02 +08:00
harttle e993118e87 Merge branch 'jaswrks-patch-1' 2017-08-04 11:27:37 +08:00
harttle 4ae63b2899 test cases for #36 2017-08-04 11:27:12 +08:00
jaswrksandGitHub 9f446ad024 Support {{- and -}} for whitespace control.
With this PR it now matches the intended functionality; i.e., https://github.com/harttle/liquidjs/wiki/Whitespace-Control
2017-08-03 06:06:35 -08:00
harttle 6f82b914cb 1.9.2 2017-08-03 13:56:09 +08:00
harttle 31397a4862 update uglify-js 2017-08-03 13:55:46 +08:00
harttle a2a076d038 refactor access seq parsing 2017-08-03 13:46:00 +08:00
jaswrksandGitHub 3dc37bf980 Bug fix for foo.bar[0].foo that is not working.
Corrects a bug where `foo.bar[0].foo` results in error: 'Cannot read property `foo` of undefined', because the sequence contains an empty string; i.e., `seq.push('')` should be avoided.

Another possible solution would be to strip empty strings from the final `seq` variable, but this PR fixes the immediate problem.
2017-08-02 10:37:11 -08:00
harttle 4ee2bc964c upgrade outdated dependencies 2017-07-28 21:25:24 +08:00
wojtask9andJun Yang ea2a5f5c3b add identation value to token (#34)
* add identation value to token

* fix lint problems

* use var instead of let
2017-07-21 12:44:27 +08:00
harttle 52e2be68ab 1.9.1 2017-07-17 01:09:22 +08:00
harttle cbde48971a rename to liquidjs 2017-07-17 01:08:51 +08:00
harttle e91cc8c950 update: auto publish after version 2017-07-14 10:42:01 +08:00
harttle 314aa6b467 1.9.0 2017-07-14 00:37:08 +08:00
harttle 14e53ed3a9 test cases for #32 2017-07-14 00:34:12 +08:00
harttle cf6d3e78fe Merge branch 'object-for-loop' of https://github.com/aleclarson/liquid-node 2017-07-13 23:24:48 +08:00
aleclarson fb52c864b1 Add isPlainObject to 'util/underscore.js' 2017-07-13 10:33:01 -04:00
harttle 9f82aec569 add test case for truncate 2017-07-13 16:28:32 +08:00
Jun YangandGitHub 29fe8dcb4b Merge pull request #31 from aleclarson/remove-stop-skip
Remove unused `stop` and `skip` from `forloop` object
2017-07-13 16:10:10 +08:00
aleclarson 2a16800305 Iterate keys of object when used with for...in loop 2017-07-12 15:33:48 -04:00
aleclarson 154cf379a8 Remove unused stop and skip from forloop object 2017-07-12 15:33:09 -04:00
harttle ed20fe6072 1.8.0 2017-04-24 21:31:56 +08:00
harttle 2632e3e97e eslint 2017-04-24 21:31:30 +08:00
harttle 82f84d96c1 1.7.9 2017-04-20 10:33:49 +08:00
harttle 1126dffd7d fix default filter use isTruthy, working on #30 2017-04-20 10:33:10 +08:00
harttle 07ec997ffd tests for truthy 2017-04-20 10:31:02 +08:00
harttle 79815784c1 1.7.8 2017-04-17 22:56:16 +08:00
harttle 2d793a63fe fix #29 2017-04-17 22:49:53 +08:00
harttle cc2b2ea5d1 1.7.7 2017-04-10 19:07:51 +08:00
Jun YangandGitHub 8ff9eeb51d Merge pull request #28 from wojtask9/master
support multiline tags
2017-04-10 19:06:16 +08:00
wojtask9 3bc7caa387 support multiline tags 2017-04-10 11:58:45 +02:00
harttle 20044c4256 1.7.6 2017-03-21 18:00:27 +08:00
chenosandJun Yang e72f295bd0 Comparison on NULL is always false (#27)
* All values in Liquid are truthy except nil and false.

* The falsy values are null, undefined and false.

* comparison on null
2017-03-21 14:54:26 +08:00
chenosandJun Yang 66774865f4 All values in Liquid are truthy except nil and false. (#26)
* All values in Liquid are truthy except nil and false.

* The falsy values are null, undefined and false.
2017-03-21 12:25:11 +08:00
harttle 2ae6874397 1.7.5 2017-03-20 15:07:10 +08:00
chenosandJun Yang b307f6ffd0 Size can also be used with dot notation (#25)
* Size can also be used with dot notation (for example, {{ my_string.size }}).

* Fixed test failed.

* Optimization
2017-03-20 15:06:32 +08:00
harttle 5b5db616e2 1.7.4 2017-03-16 19:29:16 +08:00
harttle 551a15f373 import value declaration syntax 2017-03-16 19:27:54 +08:00
ChenL 45e0fb21dc Fixed array arguments bug 2017-03-16 19:02:30 +08:00
ChenL 4fc977268f Support create variables on the filter line. 2017-03-16 18:26:10 +08:00
harttle 8231727428 update README 2017-03-16 10:44:21 +08:00
harttle 0a068ac51c 1.7.3 2017-03-16 10:40:27 +08:00
harttle 6f1d6f3d05 Merge branch 'chenos-master' 2017-03-16 10:40:09 +08:00
harttle aa52a31e90 fix: contains return false when left side equals null 2017-03-16 10:39:10 +08:00
ChenL e4056a79ee Test if an array contains a specific number/string. 2017-03-16 10:05:50 +08:00
ChenL f1d68409b1 Do not throw error in contains when variable is illegal. 2017-03-15 21:20:00 +08:00
ChenL 7ad9ce95e9 Illegal expression in contains 2017-03-15 20:38:08 +08:00
harttle ea7e334d87 1.7.2 2017-03-15 17:14:21 +08:00
harttle 4f123c1d6b Merge branch 'chenos-master' 2017-03-15 17:13:58 +08:00
harttle 0f4edc5b53 add unit test for #21 2017-03-15 17:13:05 +08:00
chenosandGitHub 48bee428d5 reversed position
eg:

- reversed limit:4 offset:2
- limit:4 reversed offset:2
- limit:4 offset:2 reversed
2017-03-15 16:59:24 +08:00
Jun YangandGitHub 2d1f05799f Update README.md 2017-02-18 17:14:51 +08:00
harttle dbc18539a0 modified: README.md 2017-02-14 10:57:57 +08:00
harttle 492f56cbfb unit test: multiple hash 2017-02-01 13:49:01 +08:00
harttle 4018ffe68b 1.7.1 2017-01-31 23:17:08 +08:00
harttle 21eefe1d7b do not trim output tags and previous \n, #19 2017-01-31 23:15:23 +08:00
harttle 0c8148c12b 1.7.0 2017-01-31 00:48:26 +08:00
harttle 7f336ded5c fix badges 2017-01-31 00:48:11 +08:00
harttle 5ecca1b761 feature: greedy trim disabled by default, working on #19 2017-01-31 00:07:46 +08:00
harttle af284daf34 1.6.2 2017-01-21 19:41:59 +08:00
harttle 21a5ac7e08 RenderError extends original error 2017-01-21 19:41:19 +08:00
harttle 7d22214cb5 remove strict_* from express arguments 2017-01-02 13:44:33 +08:00
harttle d6ca12f3bd 1.6.1 2016-12-27 00:46:53 +08:00
harttle 84f7a399c5 update README and unit test 2016-12-27 00:33:11 +08:00
harttle 5b5dfd5c00 documents for whitespace control (#17) 2016-12-27 00:09:39 +08:00
harttle d032f7f4d4 1.6.0 2016-12-26 23:38:15 +08:00
harttle 044035b8ed unit tests for #17 2016-12-26 23:37:33 +08:00
harttle 564d9cd9f4 feature: whitespace control, fixes #17 2016-12-26 23:23:58 +08:00
harttle fbb1dc8a36 test cases for filters: string->number convertion, #18 2016-12-15 23:14:49 +08:00
harttle c99dfd69e7 1.5.4 2016-12-15 22:39:52 +08:00
harttle 4719544d49 fix: number convertion for plus filter, closes #18 2016-12-15 22:38:48 +08:00
harttle 2c0ba9bfd9 1.5.3 2016-12-08 23:26:00 +08:00
harttle 89636736a4 robust date filter 2016-12-08 23:25:38 +08:00
harttle deca9677dd modified: README.md 2016-12-05 23:49:07 +08:00
harttle 543368ed89 unit test for original error for {%layout%} 2016-12-01 00:50:36 +08:00
harttle dcd7b01fa4 update tag test 2016-11-16 02:53:30 +08:00
harttle 209d3910ab 1.5.2 2016-11-16 01:07:08 +08:00
harttle 40bdd7e94a refactor: move file to token property 2016-11-16 01:06:37 +08:00
harttle 03b7ee95ed 1.5.1 2016-11-16 00:50:21 +08:00
harttle 64e9cb7044 fix nested render error message 2016-11-16 00:48:54 +08:00
65 changed files with 11133 additions and 5633 deletions
+11
View File
@@ -0,0 +1,11 @@
{
"extends": "standard",
"env": {
"browser": true,
"node": true
},
"plugins": [
"standard",
"promise"
]
}
+3 -1
View File
@@ -1,7 +1,9 @@
language: node_js
node_js:
- "node"
- "lts/*"
- "4"
before_script:
- npm install -g mocha
after_script:
- NODE_ENV=test ./node_modules/.bin/istanbul cover --report lcovonly ./node_modules/mocha/bin/_mocha -- -R spec --recursive && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage
- npm run lcov && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage
+44 -31
View File
@@ -1,27 +1,35 @@
# shopify-liquid
# liquidjs
[![NPM version](https://img.shields.io/npm/v/shopify-liquid.svg?style=flat)](https://www.npmjs.org/package/shopify-liquid)
[![Build Status](https://travis-ci.org/harttle/shopify-liquid.svg?branch=master)](https://travis-ci.org/harttle/shopify-liquid)
[![Coverage Status](https://img.shields.io/coveralls/harttle/shopify-liquid/master.svg)](https://coveralls.io/github/harttle/shopify-liquid?branch=master)
[![Dependency manager](https://img.shields.io/david/harttle/shopify-liquid.svg?style=flat)](https://david-dm.org/harttle/shopify-liquid)
[![npm](https://img.shields.io/npm/v/liquidjs.svg)](https://www.npmjs.org/package/liquidjs)
[![Build Status](https://travis-ci.org/harttle/liquidjs.svg?branch=master)](https://travis-ci.org/harttle/liquidjs)
[![Coveralls](https://img.shields.io/coveralls/harttle/liquidjs.svg)](https://coveralls.io/github/harttle/liquidjs?branch=master)
[![GitHub issues](https://img.shields.io/github/issues-closed/harttle/liquidjs.svg)](https://github.com/harttle/liquidjs/issues)
A feature-rich Liquid template engine for Node.js and browsers,
with compliance with [the Ruby version][shopify-liquid].
New to Liquid? Here's a live demo: <http://harttle.com/shopify-liquid/>
A Liquid engine implementation for both Node.js and browsers, with all [shopify/liquid][shopify/liquid] features.
Formerly known as shopify-liquid.
Live Demo: <http://harttle.com/liquidjs/>
> The Liquid template engine is implemented in Ruby originally,
> which is used by [Jekyll][jekyll] and [Github Pages][gh].
Features:
* Pretty much [builtin filters](https://github.com/harttle/shopify-liquid/wiki/Builtin-Filters) and [builtin tags](https://github.com/harttle/shopify-liquid/wiki/Builtin-Tags)
* Async rendering, especially for tags
* A wide range of [filters](https://github.com/harttle/liquidjs/wiki/Builtin-Filters) and [tags](https://github.com/harttle/liquidjs/wiki/Builtin-Tags)
* Easy tag/filter registration, allows async tags
* [any-promise][any-promise]
API Reference:
* Builtin Tags: <https://github.com/harttle/liquidjs/wiki/Builtin-Tags>
* Builtin Filters: <https://github.com/harttle/liquidjs/wiki/Builtin-Filters>
* Operators: <https://github.com/harttle/liquidjs/wiki/Operators>
* Whitespace Control: <https://github.com/harttle/liquidjs/wiki/Whitespace-Control>
Installation:
```bash
npm install --save shopify-liquid
npm install --save liquidjs
```
## Render from String
@@ -29,7 +37,7 @@ npm install --save shopify-liquid
Parse and Render:
```javascript
var Liquid = require('shopify-liquid');
var Liquid = require('liquidjs');
var engine = Liquid();
engine.parseAndRender('{{name | capitalize}}', {name: 'alice'})
@@ -52,11 +60,8 @@ engine.render(tpl, {name: 'alice'})
```javascript
var engine = Liquid({
root: path.resolve(__dirname, 'views/'), // for layouts and includes
extname: '.liquid',
cache: false,
strict_filters: false, // default: false
strict_variables: false // default: false
root: path.resolve(__dirname, 'views/'), // dirs to lookup layouts/includes
extname: '.liquid' // the default extname used for layouts/includes
});
engine.renderFile("hello.liquid", {name: 'alice'})
.then(function(html){
@@ -69,11 +74,15 @@ engine.renderFile("hello", {name: 'alice'})
});
```
## Options
The full list of options for `Liquid()` is listed as following:
* `root` is a directory or an array of directories to resolve layouts and includes, as well as the filename passed in when calling `.renderFile()`.
If an array, the files are looked up in the order they occur in the array.
Defaults to `process.cwd()`
Defaults to `["."]`
* `extname` is used to lookup the template file when filepath doesn't include an extension name. Defaults to `.liquid`
* `extname` is used to lookup the template file when filepath doesn't include an extension name. Defaults to `".liquid"`
* `cache` indicates whether or not to cache resolved templates. Defaults to `false`.
@@ -83,14 +92,17 @@ Defaults to `process.cwd()`
If set to `false`, undefined variables will be rendered as empty string.
Otherwise, undefined variables will cause an exception. Defaults to `false`.
* `trim_right` is used to strip blank characters (including ` `, `\t`, and `\r`) from the right of tags (`{% %}`) until `\n` (inclusive). Defaults to `false`.
* `trim_left` is similiar to `trim_right`, whereas the `\n` is exclusive. Defaults to `false`. See [Whitespace Control][whitespace control] for details.
* `greedy` is used to specify whether `trim_left`/`trim_right` is greedy. When set to `true`, all successive blank characters including `\n` will be trimed regardless of line breaks. Defaults to `false`.
## Use with Express.js
```javascript
// register liquid engine
app.engine('liquid', engine.express({
strict_variables: true, // Default: fasle
strict_filters: true // Default: false
}));
app.engine('liquid', engine.express());
app.set('views', './views'); // specify the views directory
app.set('view engine', 'liquid'); // set to default
```
@@ -115,11 +127,11 @@ And `window.Liquid` is what you want. There's also a [demo](demo/browser/).
var engine = window.Liquid();
var src = '{{ name | capitalize}}';
var ctx = {
name: 'welcome to Shopify Liquid'
name: 'welcome to liquidjs'
};
engine.parseAndRender(src, ctx)
.then(function(html) {
// html === Welcome to Shopify Liquid
// html === Welcome to liquidjs
});
</script>
</body>
@@ -183,7 +195,7 @@ engine.registerFilter('upper', function(v){
});
```
> See existing filter implementations: <https://github.com/harttle/shopify-liquid/blob/master/filters.js>
> See existing filter implementations: <https://github.com/harttle/liquidjs/blob/master/filters.js>
## Register Tags
@@ -200,20 +212,21 @@ engine.registerTag('upper', {
});
```
> See existing tag implementations: <https://github.com/harttle/shopify-liquid/blob/master/tags/>
> See existing tag implementations: <https://github.com/harttle/liquidjs/blob/master/tags/>
## Contribution Guide
1. Write a [test][test] to define the feature you want.
2. Just initiate an issue, or optionally:
2. File an issue, or optionally:
3. Get your test pass and make a pull request.
[nunjucks]: http://mozilla.github.io/nunjucks/
[liquid-node]: https://github.com/sirlantis/liquid-node
[shopify-liquid]: https://shopify.github.io/liquid/
[shopify/liquid]: https://shopify.github.io/liquid/
[jekyll]: http://jekyllrb.com/
[gh]: https://pages.github.com/
[releases]: https://github.com/harttle/shopify-liquid/releases
[releases]: https://github.com/harttle/liquidjs/releases
[any-promise]: https://github.com/kevinbeaty/any-promise
[test]: https://github.com/harttle/shopify-liquid/tree/master/test
[test]: https://github.com/harttle/liquidjs/tree/master/test
[caniuse-promises]: http://caniuse.com/#feat=promises
[whitespace control]: https://github.com/harttle/liquidjs/wiki/Whitespace-Control
+16 -16
View File
@@ -1,22 +1,22 @@
var express = require('express');
var app = express();
var Liquid = require('../..');
var express = require('express')
var app = express()
var Liquid = require('../..')
var engine = Liquid({
root: __dirname, // for layouts and partials
extname: '.liquid'
});
root: __dirname, // for layouts and partials
extname: '.liquid'
})
app.engine('liquid', engine.express()); // register liquid engine
app.set('views', ['./partials', './views']); // specify the views directory
app.set('view engine', 'liquid'); // set to default
app.engine('liquid', engine.express()) // register liquid engine
app.set('views', ['./partials', './views']) // specify the views directory
app.set('view engine', 'liquid') // set to default
app.get('/', function (req, res) {
var todos = ['fork and clone', 'make it better', 'make a pull request'];
res.render('todolist', {
todos: todos,
title: 'Welcome to shopify-liquid!'
});
});
var todos = ['fork and clone', 'make it better', 'make a pull request']
res.render('todolist', {
todos: todos,
title: 'Welcome to liquidjs!'
})
})
module.exports = app;
module.exports = app
+2 -2
View File
@@ -1,14 +1,14 @@
{
"name": "express-demo",
"version": "1.0.0",
"description": "Express Demo Using Shopify-Liquid",
"description": "Express Demo Using liquidjs",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "harttle",
"license": "ISC",
"license": "MIT",
"dependencies": {
"express": "^4.14.0"
}
+1580 -1540
View File
File diff suppressed because it is too large Load Diff
+1 -2
View File
File diff suppressed because one or more lines are too long
+107 -107
View File
@@ -1,127 +1,127 @@
const strftime = require('./src/util/strftime.js');
const _ = require('./src/util/underscore.js');
const strftime = require('./src/util/strftime.js')
const _ = require('./src/util/underscore.js')
const isTruthy = require('./src/syntax.js').isTruthy
var escapeMap = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&#34;',
"'": '&#39;',
};
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&#34;',
"'": '&#39;'
}
var unescapeMap = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&#34;': '"',
'&#39;': "'",
};
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&#34;': '"',
'&#39;': "'"
}
var filters = {
'abs': v => Math.abs(v),
'append': (v, arg) => v + arg,
'capitalize': str => stringify(str).charAt(0).toUpperCase() + str.slice(1),
'ceil': v => Math.ceil(v),
'date': (v, arg) => {
if (v === 'now') v = new Date();
return strftime(v, arg);
},
'default': (v, arg) => v || arg,
'divided_by': (v, arg) => Math.floor(v / arg),
'downcase': v => v.toLowerCase(),
'escape': escape,
'abs': v => Math.abs(v),
'append': (v, arg) => v + arg,
'capitalize': str => stringify(str).charAt(0).toUpperCase() + str.slice(1),
'ceil': v => Math.ceil(v),
'date': (v, arg) => {
if (v === 'now') v = new Date()
return v instanceof Date ? strftime(v, arg) : ''
},
'default': (v, arg) => isTruthy(v) ? v : arg,
'divided_by': (v, arg) => Math.floor(v / arg),
'downcase': v => v.toLowerCase(),
'escape': escape,
'escape_once': str => escape(unescape(str)),
'first': v => v[0],
'floor': v => Math.floor(v),
'join': (v, arg) => v.join(arg),
'last': v => v[v.length - 1],
'lstrip': v => stringify(v).replace(/^\s+/, ''),
'map': (arr, arg) => arr.map(v => v[arg]),
'minus': bindFixed((v, arg) => v - arg),
'modulo': bindFixed((v, arg) => v % arg),
'newline_to_br': v => v.replace(/\n/g, '<br />'),
'plus': bindFixed((v, arg) => v + arg),
'prepend': (v, arg) => arg + v,
'remove': (v, arg) => v.split(arg).join(''),
'remove_first': (v, l) => v.replace(l, ''),
'replace': (v, pattern, replacement) =>
stringify(v).split(pattern).join(replacement),
'replace_first': (v, arg1, arg2) => stringify(v).replace(arg1, arg2),
'reverse': v => v.reverse(),
'round': (v, arg) => {
var amp = Math.pow(10, arg || 0);
return Math.round(v * amp, arg) / amp;
},
'rstrip': str => stringify(str).replace(/\s+$/, ''),
'size': v => v.length,
'slice': (v, begin, length) =>
v.substr(begin, length === undefined ? 1 : length),
'sort': (v, arg) => v.sort(arg),
'split': (v, arg) => stringify(v).split(arg),
'strip': (v) => stringify(v).trim(),
'strip_html': v => stringify(v).replace(/<\/?\s*\w+\s*\/?>/g, ''),
'strip_newlines': v => stringify(v).replace(/\n/g, ''),
'times': (v, arg) => v * arg,
'truncate': (v, l, o) => {
v = stringify(v);
o = (o === undefined) ? '...' : o;
l = l || 16;
if (v.length <= l) return v;
return v.substr(0, l - o.length) + o;
},
'truncatewords': (v, l, o) => {
if (o === undefined) o = '...';
var arr = v.split(' ');
var ret = arr.slice(0, l).join(' ');
if (arr.length > l) ret += o;
return ret;
},
'uniq': function(arr) {
var u = {};
return (arr || []).filter(val => {
if (u.hasOwnProperty(val)) {
return false;
}
u[val] = true;
return true;
});
},
'upcase': str => stringify(str).toUpperCase(),
'url_encode': encodeURIComponent
};
function escape(str) {
return stringify(str).replace(/&|<|>|"|'/g, m => escapeMap[m]);
'escape_once': str => escape(unescape(str)),
'first': v => v[0],
'floor': v => Math.floor(v),
'join': (v, arg) => v.join(arg),
'last': v => v[v.length - 1],
'lstrip': v => stringify(v).replace(/^\s+/, ''),
'map': (arr, arg) => arr.map(v => v[arg]),
'minus': bindFixed((v, arg) => v - arg),
'modulo': bindFixed((v, arg) => v % arg),
'newline_to_br': v => v.replace(/\n/g, '<br />'),
'plus': bindFixed((v, arg) => Number(v) + Number(arg)),
'prepend': (v, arg) => arg + v,
'remove': (v, arg) => v.split(arg).join(''),
'remove_first': (v, l) => v.replace(l, ''),
'replace': (v, pattern, replacement) =>
stringify(v).split(pattern).join(replacement),
'replace_first': (v, arg1, arg2) => stringify(v).replace(arg1, arg2),
'reverse': v => v.reverse(),
'round': (v, arg) => {
var amp = Math.pow(10, arg || 0)
return Math.round(v * amp, arg) / amp
},
'rstrip': str => stringify(str).replace(/\s+$/, ''),
'size': v => v.length,
'slice': (v, begin, length) =>
v.substr(begin, length === undefined ? 1 : length),
'sort': (v, arg) => v.sort(arg),
'split': (v, arg) => stringify(v).split(arg),
'strip': (v) => stringify(v).trim(),
'strip_html': v => stringify(v).replace(/<\/?\s*\w+\s*\/?>/g, ''),
'strip_newlines': v => stringify(v).replace(/\n/g, ''),
'times': (v, arg) => v * arg,
'truncate': (v, l, o) => {
v = stringify(v)
o = (o === undefined) ? '...' : o
l = l || 16
if (v.length <= l) return v
return v.substr(0, l - o.length) + o
},
'truncatewords': (v, l, o) => {
if (o === undefined) o = '...'
var arr = v.split(' ')
var ret = arr.slice(0, l).join(' ')
if (arr.length > l) ret += o
return ret
},
'uniq': function (arr) {
var u = {}
return (arr || []).filter(val => {
if (u.hasOwnProperty(val)) {
return false
}
u[val] = true
return true
})
},
'upcase': str => stringify(str).toUpperCase(),
'url_encode': encodeURIComponent
}
function unescape(str) {
return stringify(str).replace(/&(amp|lt|gt|#34|#39);/g, m => unescapeMap[m]);
function escape (str) {
return stringify(str).replace(/&|<|>|"|'/g, m => escapeMap[m])
}
function getFixed(v) {
var p = (v + "").split(".");
return (p.length > 1) ? p[1].length : 0;
function unescape (str) {
return stringify(str).replace(/&(amp|lt|gt|#34|#39);/g, m => unescapeMap[m])
}
function getMaxFixed(l, r) {
return Math.max(getFixed(l), getFixed(r));
function getFixed (v) {
var p = (v + '').split('.')
return (p.length > 1) ? p[1].length : 0
}
function stringify(obj) {
obj = obj || "";
return obj + '';
function getMaxFixed (l, r) {
return Math.max(getFixed(l), getFixed(r))
}
function bindFixed(cb) {
return (l, r) => {
var f = getMaxFixed(l, r);
return cb(l, r).toFixed(f);
};
function stringify (obj) {
return obj + ''
}
function registerAll(liquid) {
return _.forOwn(filters, (func, name) => liquid.registerFilter(name, func));
function bindFixed (cb) {
return (l, r) => {
var f = getMaxFixed(l, r)
return cb(l, r).toFixed(f)
}
}
registerAll.filters = filters;
module.exports = registerAll;
function registerAll (liquid) {
return _.forOwn(filters, (func, name) => liquid.registerFilter(name, func))
}
registerAll.filters = filters
module.exports = registerAll
+133 -141
View File
@@ -1,152 +1,144 @@
const Scope = require('./src/scope');
const _ = require('./src/util/underscore.js');
const assert = require('./src/util/assert.js');
const tokenizer = require('./src/tokenizer.js');
const statFileAsync = require('./src/util/fs.js').statFileAsync;
const readFileAsync = require('./src/util/fs.js').readFileAsync;
const path = require('path');
const Render = require('./src/render.js');
const lexical = require('./src/lexical.js');
const Tag = require('./src/tag.js');
const Filter = require('./src/filter.js');
const Parser = require('./src/parser');
const Syntax = require('./src/syntax.js');
const tags = require('./tags');
const filters = require('./filters');
const Promise = require('any-promise');
const anySeries = require('./src/util/promise.js').anySeries;
const Errors = require('./src/util/error.js');
const Scope = require('./src/scope')
const _ = require('./src/util/underscore.js')
const assert = require('./src/util/assert.js')
const tokenizer = require('./src/tokenizer.js')
const statFileAsync = require('./src/util/fs.js').statFileAsync
const readFileAsync = require('./src/util/fs.js').readFileAsync
const path = require('path')
const Render = require('./src/render.js')
const lexical = require('./src/lexical.js')
const Tag = require('./src/tag.js')
const Filter = require('./src/filter.js')
const Parser = require('./src/parser')
const Syntax = require('./src/syntax.js')
const tags = require('./tags')
const filters = require('./filters')
const Promise = require('any-promise')
const anySeries = require('./src/util/promise.js').anySeries
const Errors = require('./src/util/error.js')
var _engine = {
init: function(tag, filter, options) {
if (options.cache) {
this.cache = {};
}
this.options = options;
this.tag = tag;
this.filter = filter;
this.parser = Parser(tag, filter);
this.renderer = Render();
tags(this);
filters(this);
return this;
},
parse: function(html) {
var tokens = tokenizer.parse(html);
return this.parser.parse(tokens);
},
render: function(tpl, ctx, opts) {
opts = _.assign({}, this.options, opts);
var scope = Scope.factory(ctx, opts);
return this.renderer.renderTemplates(tpl, scope);
},
parseAndRender: function(html, ctx, opts) {
return Promise.resolve()
.then(() => this.parse(html))
.then(tpl => this.render(tpl, ctx, opts))
.catch(e => {
if (e instanceof Errors.RenderBreakError) {
return e.html;
}
throw e;
});
},
renderFile: function(filepath, ctx, opts) {
opts = _.assign({}, opts);
return this.getTemplate(filepath, opts.root)
.then(templates => this.render(templates, ctx, opts))
.catch(e => {
e.file = filepath;
throw e;
});
},
evalOutput: function(str, scope) {
var tpl = this.parser.parseOutput(str.trim());
return this.renderer.evalOutput(tpl, scope);
},
registerFilter: function(name, filter) {
return this.filter.register(name, filter);
},
registerTag: function(name, tag) {
return this.tag.register(name, tag);
},
lookup: function(filepath, root) {
root = this.options.root.concat(root || []);
root = _.uniq(root);
var paths = root.map(root => path.resolve(root, filepath));
return anySeries(paths, path => statFileAsync(path).then(() => path))
.catch((e) => {
if (e.code === 'ENOENT') {
e.message = `Failed to lookup ${filepath} in: ${root}`;
}
throw e;
});
},
getTemplate: function(filepath, root) {
if(!path.extname(filepath)){
filepath += this.options.extname;
}
return this
.lookup(filepath, root)
.then(filepath => {
if (this.options.cache) {
var tpl = this.cache[filepath];
if (tpl) {
return Promise.resolve(tpl);
}
return readFileAsync(filepath)
.then(str => this.parse(str))
.then(tpl => this.cache[filepath] = tpl);
} else {
return readFileAsync(filepath).then(str => this.parse(str));
}
});
},
express: function(opts) {
opts = opts || {};
var self = this;
return function(filePath, ctx, callback) {
assert(_.isArray(this.root) || _.isString(this.root),
'illegal views root, are you using express.js?');
opts.root = this.root;
self.renderFile(filePath, ctx, opts)
.then(html => callback(null, html))
.catch(e => callback(e));
};
init: function (tag, filter, options) {
if (options.cache) {
this.cache = {}
}
};
this.options = options
this.tag = tag
this.filter = filter
this.parser = Parser(tag, filter)
this.renderer = Render()
function factory(options) {
options = _.assign({}, options);
options.root = normalizeStringArray(options.root);
if (!options.root.length) options.root = ['.'];
tags(this)
filters(this)
options.extname = options.extname || '.liquid';
var engine = Object.create(_engine);
engine.init(Tag(), Filter(options), options);
return engine;
return this
},
parse: function (html, filepath) {
var tokens = tokenizer.parse(html, filepath, this.options)
return this.parser.parse(tokens)
},
render: function (tpl, ctx, opts) {
opts = _.assign({}, this.options, opts)
var scope = Scope.factory(ctx, opts)
return this.renderer.renderTemplates(tpl, scope)
},
parseAndRender: function (html, ctx, opts) {
return Promise.resolve()
.then(() => this.parse(html))
.then(tpl => this.render(tpl, ctx, opts))
},
renderFile: function (filepath, ctx, opts) {
opts = _.assign({}, opts)
return this.getTemplate(filepath, opts.root)
.then(templates => this.render(templates, ctx, opts))
},
evalOutput: function (str, scope) {
var tpl = this.parser.parseOutput(str.trim())
return this.renderer.evalOutput(tpl, scope)
},
registerFilter: function (name, filter) {
return this.filter.register(name, filter)
},
registerTag: function (name, tag) {
return this.tag.register(name, tag)
},
lookup: function (filepath, root) {
root = this.options.root.concat(root || [])
root = _.uniq(root)
var paths = root.map(root => path.resolve(root, filepath))
return anySeries(paths, path => statFileAsync(path).then(() => path))
.catch((e) => {
e.message = `${e.code}: Failed to lookup ${filepath} in: ${root}`
throw e
})
},
getTemplate: function (filepath, root) {
if (!path.extname(filepath)) {
filepath += this.options.extname
}
return this
.lookup(filepath, root)
.then(filepath => {
if (this.options.cache) {
var tpl = this.cache[filepath]
if (tpl) {
return Promise.resolve(tpl)
}
return readFileAsync(filepath)
.then(str => this.parse(str))
.then(tpl => (this.cache[filepath] = tpl))
} else {
return readFileAsync(filepath).then(str => this.parse(str, filepath))
}
})
},
express: function (opts) {
opts = opts || {}
var self = this
return function (filePath, ctx, callback) {
assert(Array.isArray(this.root) || _.isString(this.root),
'illegal views root, are you using express.js?')
opts.root = this.root
self.renderFile(filePath, ctx, opts)
.then(html => callback(null, html))
.catch(e => callback(e))
}
}
}
function normalizeStringArray(value) {
if (_.isArray(value)) return value;
if (_.isString(value)) return [value];
return [];
function factory (options) {
options = _.assign({
root: ['.'],
cache: false,
extname: '.liquid',
trim_right: false,
trim_left: false,
strict_filters: false,
strict_variables: false
}, options)
options.root = normalizeStringArray(options.root)
var engine = Object.create(_engine)
engine.init(Tag(), Filter(options), options)
return engine
}
factory.lexical = lexical;
factory.isTruthy = Syntax.isTruthy;
factory.isFalsy = Syntax.isFalsy;
factory.evalExp = Syntax.evalExp;
factory.evalValue = Syntax.evalValue;
function normalizeStringArray (value) {
if (Array.isArray(value)) return value
if (_.isString(value)) return [value]
return []
}
factory.lexical = lexical
factory.isTruthy = Syntax.isTruthy
factory.isFalsy = Syntax.isFalsy
factory.evalExp = Syntax.evalExp
factory.evalValue = Syntax.evalValue
factory.Types = {
ParseError: Errors.ParseError,
TokenizationEroor: Errors.TokenizationError,
RenderBreakError: Errors.RenderBreakError,
AssertionError: Errors.AssertionError
};
ParseError: Errors.ParseError,
TokenizationEroor: Errors.TokenizationError,
RenderBreakError: Errors.RenderBreakError,
AssertionError: Errors.AssertionError
}
module.exports = factory;
module.exports = factory
+4819
View File
File diff suppressed because it is too large Load Diff
+31 -21
View File
@@ -1,18 +1,21 @@
{
"name": "shopify-liquid",
"version": "1.5.0",
"description": "A feature-rich Liquid template engine for Node.js and browsers, with compliance with the Ruby version.",
"name": "liquidjs",
"version": "1.9.7",
"description": "A Liquid template engine for Node.js and browsers, with all shopify/liquid features.",
"main": "index.js",
"scripts": {
"test": "mocha --recursive",
"lint": "eslint src/ test/",
"test": "npm run lint && mocha --recursive",
"coverage": "NODE_ENV=test istanbul cover --report html ./node_modules/mocha/bin/_mocha -- -R spec --recursive",
"lcov": "NODE_ENV=test istanbul cover --report lcovonly ./node_modules/mocha/bin/_mocha -- -R spec --recursive",
"dist": "make dist",
"preversion": "npm test",
"version": "npm run dist && git add -A dist",
"postversion": "git push && git push --tags"
"postversion": "git push && git push --tags && npm publish"
},
"repository": {
"type": "git",
"url": "git+https://github.com/harttle/shopify-liquid.git"
"url": "git+https://github.com/harttle/liquidjs.git"
},
"keywords": [
"liquid",
@@ -24,26 +27,33 @@
"author": "Harttle",
"license": "MIT",
"bugs": {
"url": "https://github.com/harttle/shopify-liquid/issues"
"url": "https://github.com/harttle/liquidjs/issues"
},
"homepage": "https://github.com/harttle/shopify-liquid#readme",
"homepage": "https://github.com/harttle/liquidjs#readme",
"dependencies": {
"any-promise": "^1.3.0"
},
"devDependencies": {
"babel-preset-es2015": "^6.14.0",
"babel-preset-es2015": "^6.24.1",
"babelify": "^7.3.0",
"browserify": "^13.1.0",
"chai": "^3.5.0",
"chai-as-promised": "^5.3.0",
"coveralls": "^2.11.9",
"express": "^4.14.0",
"istanbul": "^0.4.3",
"mocha": "^3.0.2",
"mock-fs": "^3.9.0",
"sinon": "^1.17.4",
"sinon-chai": "^2.8.0",
"supertest": "^2.0.0",
"uglifyjs": "^2.4.10"
"browserify": "^14.4.0",
"chai": "^4.1.2",
"chai-as-promised": "^7.1.1",
"coveralls": "^3.0.0",
"eslint": "^4.8.0",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-mocha": "^4.11.0",
"eslint-plugin-node": "^5.2.0",
"eslint-plugin-promise": "^3.5.0",
"eslint-plugin-standard": "^3.0.1",
"express": "^4.16.1",
"istanbul": "^0.4.5",
"mocha": "^4.0.0",
"mock-fs": "^4.4.1",
"sinon": "^4.0.1",
"sinon-chai": "^2.14.0",
"supertest": "^3.0.0",
"uglify-js": "^3.1.3"
}
}
+56 -56
View File
@@ -1,66 +1,66 @@
const lexical = require('./lexical.js');
const Syntax = require('./syntax.js');
const assert = require('./util/assert.js');
const _ = require('./util/underscore.js');
const lexical = require('./lexical.js')
const Syntax = require('./syntax.js')
const assert = require('./util/assert.js')
const _ = require('./util/underscore.js')
var valueRE = new RegExp(`${lexical.value.source}`, 'g');
var valueRE = new RegExp(`${lexical.value.source}`, 'g')
module.exports = function(options) {
options = _.assign({}, options);
var filters = {};
module.exports = function (options) {
options = _.assign({}, options)
var filters = {}
var _filterInstance = {
render: function(output, scope) {
var args = this.args.map(arg => Syntax.evalValue(arg, scope));
args.unshift(output);
return this.filter.apply(null, args);
},
parse: function(str) {
var match = lexical.filterLine.exec(str);
assert(match, 'illegal filter: ' + str);
var _filterInstance = {
render: function (output, scope) {
var args = this.args.map(arg => Syntax.evalValue(arg, scope))
args.unshift(output)
return this.filter.apply(null, args)
},
parse: function (str) {
var match = lexical.filterLine.exec(str)
assert(match, 'illegal filter: ' + str)
var name = match[1], argList = match[2] || '', filter = filters[name];
if (typeof filter !== 'function'){
if(options.strict_filters){
throw new TypeError(`undefined filter: ${name}`);
}
this.name= name;
this.filter= x => x;
this.args= [];
return this;
//return {
//name: name,
//error: new TypeError(`undefined filter: ${name}`)
//};
}
var args = [];
while(match = valueRE.exec(argList.trim())){
args.push(match[0]);
}
this.name = name;
this.filter = filter;
this.args = args;
return this;
var name = match[1]
var argList = match[2] || ''
var filter = filters[name]
if (typeof filter !== 'function') {
if (options.strict_filters) {
throw new TypeError(`undefined filter: ${name}`)
}
};
this.name = name
this.filter = x => x
this.args = []
return this
}
function construct(str) {
var instance = Object.create(_filterInstance);
return instance.parse(str);
var args = []
while ((match = valueRE.exec(argList.trim()))) {
var v = match[0]
var re = new RegExp(`${v}\\s*:`, 'g')
re.test(match.input) ? args.push(`'${v}'`) : args.push(v)
}
this.name = name
this.filter = filter
this.args = args
return this
}
}
function register(name, filter) {
filters[name] = filter;
}
function construct (str) {
var instance = Object.create(_filterInstance)
return instance.parse(str)
}
function clear() {
filters = {};
}
function register (name, filter) {
filters[name] = filter
}
return {
construct, register, clear
};
};
function clear () {
filters = {}
}
return {
construct, register, clear
}
}
+86 -61
View File
@@ -1,91 +1,116 @@
// quote related
var singleQuoted = /'[^']*'/;
var doubleQuoted = /"[^"]*"/;
var quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`);
var quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`);
var singleQuoted = /'[^']*'/
var doubleQuoted = /"[^"]*"/
var quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
var quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`)
// basic types
var integer = /-?\d+/;
var number = /-?\d+\.?\d*|\.?\d+/;
var bool = /true|false/;
var integer = /-?\d+/
var number = /-?\d+\.?\d*|\.?\d+/
var bool = /true|false/
// peoperty access
var identifier = /[\w-]+/;
var subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`);
var literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`);
var variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`);
var identifier = /[\w-]+/
var subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`)
var literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`)
var variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`)
// range related
var rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`);
var range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`);
var rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`);
var rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`)
var range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`)
var rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`)
var value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`);
var value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
// hash related
var hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`);
var hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g');
var hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`)
var hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
// full match
var tagLine = new RegExp(`^\\s*(${identifier.source})\\s*(.*)\\s*$`);
var literalLine = new RegExp(`^${literal.source}$`, 'i');
var variableLine = new RegExp(`^${variable.source}$`);
var numberLine = new RegExp(`^${number.source}$`);
var boolLine = new RegExp(`^${bool.source}$`, 'i');
var quotedLine = new RegExp(`^${quoted.source}$`);
var rangeLine = new RegExp(`^${rangeCapture.source}$`);
var integerLine = new RegExp(`^${integer.source}$`);
var tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`)
var literalLine = new RegExp(`^${literal.source}$`, 'i')
var variableLine = new RegExp(`^${variable.source}$`)
var numberLine = new RegExp(`^${number.source}$`)
var boolLine = new RegExp(`^${bool.source}$`, 'i')
var quotedLine = new RegExp(`^${quoted.source}$`)
var rangeLine = new RegExp(`^${rangeCapture.source}$`)
var integerLine = new RegExp(`^${integer.source}$`)
// filter related
var valueList = new RegExp(`${value.source}(\\s*,\\s*${value.source})*`);
var filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g');
var filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`);
var filterLine = new RegExp(`^${filterCapture.source}$`);
var valueDeclaration = new RegExp(`(?:${identifier.source}\\s*:\\s*)?${value.source}`)
var valueList = new RegExp(`${valueDeclaration.source}(\\s*,\\s*${valueDeclaration.source})*`)
var filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g')
var filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`)
var filterLine = new RegExp(`^${filterCapture.source}$`)
var operators = [
/\s+or\s+/,
/\s+and\s+/,
/==|!=|<=|>=|<|>|\s+contains\s+/
];
/\s+or\s+/,
/\s+and\s+/,
/==|!=|<=|>=|<|>|\s+contains\s+/
]
function isInteger(str){
return integerLine.test(str);
function isInteger (str) {
return integerLine.test(str)
}
function isLiteral(str) {
return literalLine.test(str);
function isLiteral (str) {
return literalLine.test(str)
}
function isRange(str) {
return rangeLine.test(str);
function isRange (str) {
return rangeLine.test(str)
}
function isVariable(str) {
return variableLine.test(str);
function isVariable (str) {
return variableLine.test(str)
}
function matchValue(str) {
return value.exec(str);
function matchValue (str) {
return value.exec(str)
}
function parseLiteral(str) {
var res;
if (res = str.match(numberLine)) {
return Number(str);
}
if (res = str.match(boolLine)) {
return str.toLowerCase() === 'true';
}
if (res = str.match(quotedLine)) {
return str.slice(1, -1);
}
function parseLiteral (str) {
var res = str.match(numberLine)
if (res) {
return Number(str)
}
res = str.match(boolLine)
if (res) {
return str.toLowerCase() === 'true'
}
res = str.match(quotedLine)
if (res) {
return str.slice(1, -1)
}
throw new TypeError(`cannot parse '${str}' as literal`)
}
module.exports = {
quoted, number, bool, literal, filter, integer,
hash, hashCapture,
range, rangeCapture,
identifier, value, quoteBalanced, operators,
quotedLine, numberLine, boolLine, rangeLine, literalLine, filterLine, tagLine,
isLiteral, isVariable, parseLiteral, isRange, matchValue, isInteger
};
quoted,
number,
bool,
literal,
filter,
integer,
hash,
hashCapture,
range,
rangeCapture,
identifier,
value,
quoteBalanced,
operators,
quotedLine,
numberLine,
boolLine,
rangeLine,
literalLine,
filterLine,
tagLine,
isLiteral,
isVariable,
parseLiteral,
isRange,
matchValue,
isInteger
}
+15 -11
View File
@@ -1,13 +1,17 @@
var operators = {
'==': (l, r) => l == r,
'!=': (l, r) => l != r,
'>': (l, r) => l > r,
'<': (l, r) => l < r,
'>=': (l, r) => l >= r,
'<=': (l, r) => l <= r,
'contains': (l, r) => l.indexOf(r) > -1,
'and': (l, r) => l && r,
'or': (l, r) => l || r
};
'==': (l, r) => l === r,
'!=': (l, r) => l !== r,
'>': (l, r) => l !== null && r !== null && l > r,
'<': (l, r) => l !== null && r !== null && l < r,
'>=': (l, r) => l !== null && r !== null && l >= r,
'<=': (l, r) => l !== null && r !== null && l <= r,
'contains': (l, r) => {
if (!l) return false
if (typeof l.indexOf !== 'function') return false
return l.indexOf(r) > -1
},
'and': (l, r) => l && r,
'or': (l, r) => l || r
}
module.exports = operators;
module.exports = operators
+91 -91
View File
@@ -1,105 +1,105 @@
const lexical = require('./lexical.js');
const ParseError = require('./util/error.js').ParseError;
const assert = require('./util/assert.js');
const lexical = require('./lexical.js')
const ParseError = require('./util/error.js').ParseError
const assert = require('./util/assert.js')
module.exports = function(Tag, Filter) {
var stream = {
init: function(tokens) {
this.tokens = tokens;
this.handlers = {};
return this;
},
on: function(name, cb) {
this.handlers[name] = cb;
return this;
},
trigger: function(event, arg) {
var h = this.handlers[event];
if (typeof h === 'function') {
h(arg);
return true;
}
},
start: function() {
this.trigger('start');
var token;
while (!this.stopRequested && (token = this.tokens.shift())) {
if (this.trigger('token', token)) continue;
if (token.type == 'tag' &&
this.trigger(`tag:${token.name}`, token)) {
continue;
}
var template = parseToken(token, this.tokens);
this.trigger('template', template);
}
if (!this.stopRequested) this.trigger('end');
return this;
},
stop: function() {
this.stopRequested = true;
return this;
module.exports = function (Tag, Filter) {
var stream = {
init: function (tokens) {
this.tokens = tokens
this.handlers = {}
return this
},
on: function (name, cb) {
this.handlers[name] = cb
return this
},
trigger: function (event, arg) {
var h = this.handlers[event]
if (typeof h === 'function') {
h(arg)
return true
}
},
start: function () {
this.trigger('start')
var token
while (!this.stopRequested && (token = this.tokens.shift())) {
if (this.trigger('token', token)) continue
if (token.type === 'tag' &&
this.trigger(`tag:${token.name}`, token)) {
continue
}
};
function parse(tokens) {
var token, templates = [];
while (token = tokens.shift()) {
templates.push(parseToken(token, tokens));
}
return templates;
var template = parseToken(token, this.tokens)
this.trigger('template', template)
}
if (!this.stopRequested) this.trigger('end')
return this
},
stop: function () {
this.stopRequested = true
return this
}
}
function parseToken(token, tokens) {
try {
var tpl = null;
if (token.type === 'tag') {
tpl = parseTag(token, tokens);
} else if (token.type === 'output') {
tpl = parseOutput(token.value);
} else { // token.type === 'html'
tpl = token;
}
tpl.token = token;
return tpl;
} catch (e) {
throw new ParseError(e, token);
}
function parse (tokens) {
var token
var templates = []
while ((token = tokens.shift())) {
templates.push(parseToken(token, tokens))
}
return templates
}
function parseTag(token, tokens) {
if (token.name === 'continue' || token.name === 'break') return token;
return Tag.construct(token, tokens);
function parseToken (token, tokens) {
try {
var tpl = null
if (token.type === 'tag') {
tpl = parseTag(token, tokens)
} else if (token.type === 'output') {
tpl = parseOutput(token.value)
} else { // token.type === 'html'
tpl = token
}
tpl.token = token
return tpl
} catch (e) {
throw new ParseError(e, token)
}
}
function parseOutput(str) {
var match = lexical.matchValue(str);
assert(match, `illegal output string: ${str}`);
function parseTag (token, tokens) {
if (token.name === 'continue' || token.name === 'break') return token
return Tag.construct(token, tokens)
}
var initial = match[0];
str = str.substr(match.index + match[0].length);
function parseOutput (str) {
var match = lexical.matchValue(str)
assert(match, `illegal output string: ${str}`)
var filters = [];
while (match = lexical.filter.exec(str)) {
filters.push([match[0].trim()]);
}
var initial = match[0]
str = str.substr(match.index + match[0].length)
return {
type: 'output',
initial: initial,
filters: filters.map(str => Filter.construct(str))
};
}
function parseStream(tokens) {
var s = Object.create(stream);
return s.init(tokens);
var filters = []
while ((match = lexical.filter.exec(str))) {
filters.push([match[0].trim()])
}
return {
parse,
parseTag,
parseStream,
parseOutput
};
};
type: 'output',
initial: initial,
filters: filters.map(str => Filter.construct(str))
}
}
function parseStream (tokens) {
var s = Object.create(stream)
return s.init(tokens)
}
return {
parse,
parseTag,
parseStream,
parseOutput
}
}
+57 -57
View File
@@ -1,68 +1,68 @@
const Syntax = require('./syntax.js');
const Promise = require('any-promise');
const mapSeries = require('./util/promise.js').mapSeries;
const RenderBreakError = require('./util/error.js').RenderBreakError;
const RenderError = require('./util/error.js').RenderError;
const assert = require('./util/assert.js');
const Syntax = require('./syntax.js')
const Promise = require('any-promise')
const mapSeries = require('./util/promise.js').mapSeries
const RenderBreakError = require('./util/error.js').RenderBreakError
const RenderError = require('./util/error.js').RenderError
const assert = require('./util/assert.js')
var render = {
renderTemplates: function(templates, scope) {
assert(scope, 'unable to evalTemplates: scope undefined');
renderTemplates: function (templates, scope) {
assert(scope, 'unable to evalTemplates: scope undefined')
var html = '';
return mapSeries(templates, (tpl) => {
return renderTemplate.call(this, tpl)
.then(partial => html += partial)
.catch(e => {
if (e instanceof RenderBreakError) {
e.resolvedHTML = html;
throw e;
}
throw new RenderError(e, tpl);
});
}).then(() => html);
var html = ''
return mapSeries(templates, (tpl) => {
return renderTemplate.call(this, tpl)
.then(partial => (html += partial))
.catch(e => {
if (e instanceof RenderBreakError) {
e.resolvedHTML = html
throw e
}
throw new RenderError(e, tpl)
})
}).then(() => html)
function renderTemplate(template) {
if (template.type === 'tag') {
return this.renderTag(template, scope)
.then(partial => partial === undefined ? '' : partial);
} else if (template.type === 'output') {
return Promise.resolve()
.then(() => this.evalOutput(template, scope))
.then(partial => partial === undefined ? '' : stringify(partial));
} else { // template.type === 'html'
return Promise.resolve(template.value);
}
}
},
renderTag: function(template, scope) {
if (template.name === 'continue') {
return Promise.reject(new RenderBreakError('continue'));
}
if (template.name === 'break') {
return Promise.reject(new RenderBreakError('break'));
}
return template.render(scope);
},
evalOutput: function(template, scope) {
assert(scope, 'unable to evalOutput: scope undefined');
return template.filters.reduce(
(prev, filter) => filter.render(prev, scope),
Syntax.evalExp(template.initial, scope));
function renderTemplate (template) {
if (template.type === 'tag') {
return this.renderTag(template, scope)
.then(partial => partial === undefined ? '' : partial)
} else if (template.type === 'output') {
return Promise.resolve()
.then(() => this.evalOutput(template, scope))
.then(partial => partial === undefined ? '' : stringify(partial))
} else { // template.type === 'html'
return Promise.resolve(template.value)
}
}
};
},
function factory() {
var instance = Object.create(render);
return instance;
renderTag: function (template, scope) {
if (template.name === 'continue') {
return Promise.reject(new RenderBreakError('continue'))
}
if (template.name === 'break') {
return Promise.reject(new RenderBreakError('break'))
}
return template.render(scope)
},
evalOutput: function (template, scope) {
assert(scope, 'unable to evalOutput: scope undefined')
return template.filters.reduce(
(prev, filter) => filter.render(prev, scope),
Syntax.evalExp(template.initial, scope))
}
}
function stringify(val) {
if (typeof val === 'string') return val;
return JSON.stringify(val);
function factory () {
var instance = Object.create(render)
return instance
}
module.exports = factory;
function stringify (val) {
if (typeof val === 'string') return val
return JSON.stringify(val)
}
module.exports = factory
+178 -164
View File
@@ -1,172 +1,186 @@
const _ = require('./util/underscore.js');
const lexical = require('./lexical.js');
const assert = require('./util/assert.js');
const _ = require('./util/underscore.js')
const lexical = require('./lexical.js')
const assert = require('./util/assert.js')
var Scope = {
getAll: function() {
var ctx = {};
for (var i = this.scopes.length - 1; i >= 0; i--) {
_.assign(ctx, this.scopes[i]);
}
return ctx;
},
get: function(str) {
for (var i = this.scopes.length - 1; i >= 0; i--) {
try {
return this.getPropertyByPath(this.scopes[i], str);
} catch (e) {
if (/undefined variable/.test(e.message)) {
continue;
}
if (/Cannot read property/.test(e.message)) {
if (this.opts.strict_variables) {
e.message += ': ' + str;
throw e;
} else {
continue;
}
} else {
e.message += ': ' + str;
throw e;
}
}
}
if (this.opts.strict_variables) {
throw new TypeError('undefined variable: ' + str);
}
},
set: function(k, v) {
this.setPropertyByPath(this.scopes[this.scopes.length - 1], k, v);
return this;
},
push: function(ctx) {
assert(ctx, `trying to push ${ctx} into scopes`);
return this.scopes.push(ctx);
},
pop: function() {
return this.scopes.pop();
},
unshift: function(ctx) {
assert(ctx, `trying to push ${ctx} into scopes`);
return this.scopes.unshift(ctx);
},
shift: function() {
return this.scopes.shift();
},
setPropertyByPath: function(obj, path, val) {
if (_.isString(path)) {
var paths = path.replace(/\[/g, '.').replace(/\]/g, '').split('.');
for (var i = 0; i < paths.length; i++) {
var key = paths[i];
if (i === paths.length - 1) {
return obj[key] = val;
}
if (undefined === obj[key]) obj[key] = {};
// case for readonly objects
obj = obj[key] || {};
}
}
},
getPropertyByPath: function(obj, path) {
var paths = this.propertyAccessSeq(path + '');
var varName = paths.shift();
if (!obj.hasOwnProperty(varName)) {
throw new TypeError('undefined variable');
}
var variable = obj[varName];
paths.forEach(p => variable = variable[p]);
return variable;
},
/*
* Parse property access sequence from access string
* @example
* accessSeq("foo.bar") // ['foo', 'bar']
* accessSeq("foo['bar']") // ['foo', 'bar']
* accessSeq("foo['b]r']") // ['foo', 'b]r']
* accessSeq("foo[bar.coo]") // ['foo', 'bar'], for bar.coo == 'bar'
*/
propertyAccessSeq: function(str) {
var seq = [],
name = '';
for (var i = 0; i < str.length; i++) {
if (str[i] === '[') {
seq.push(name);
name = '';
var delemiter = str[i + 1];
// foo[bar.coo]
if (delemiter !== "'" && delemiter !== '"') {
var j = matchRightBracket(str, i + 1);
assert(j !== -1, `unbalanced []: ${str}`);
name = str.slice(i + 1, j);
// foo[1]
if (lexical.isInteger(name)) {
seq.push(name);
}
// foo["bar"]
else {
seq.push(this.get(name));
}
name = '';
i = j;
}
// foo["bar"]
else {
j = str.indexOf(delemiter, i + 2);
assert(j !== -1, `unbalanced ${delemiter}: ${str}`);
name = str.slice(i + 2, j);
seq.push(name);
name = '';
i = j + 1;
}
}
// foo.bar
else if (str[i] === ".") {
seq.push(name);
name = '';
}
//foo.bar
else {
name += str[i];
}
}
if (name.length) seq.push(name);
return seq;
getAll: function () {
var ctx = {}
for (var i = this.scopes.length - 1; i >= 0; i--) {
_.assign(ctx, this.scopes[i])
}
};
function matchRightBracket(str, begin) {
var stack = 1; // count of '[' - count of ']'
for (var i = begin; i < str.length; i++) {
if (str[i] === '[') {
stack++;
}
if (str[i] === ']') {
stack--;
if (stack === 0) {
return i;
}
}
return ctx
},
get: function (str) {
try {
return this.getPropertyByPath(this.scopes, str)
} catch (e) {
if (!/undefined variable/.test(e.message) || this.opts.strict_variables) {
throw e
}
}
return -1;
},
set: function (k, v) {
var scope = this.findScopeFor(k)
setPropertyByPath(scope, k, v)
return this
},
push: function (ctx) {
assert(ctx, `trying to push ${ctx} into scopes`)
return this.scopes.push(ctx)
},
pop: function () {
return this.scopes.pop()
},
findScopeFor: function (key) {
var i = this.scopes.length - 1
while (i >= 0 && !(key in this.scopes[i])) {
i--
}
if (i < 0) {
i = this.scopes.length - 1
}
return this.scopes[i]
},
unshift: function (ctx) {
assert(ctx, `trying to push ${ctx} into scopes`)
return this.scopes.unshift(ctx)
},
shift: function () {
return this.scopes.shift()
},
getPropertyByPath: function (scopes, path) {
var paths = this.propertyAccessSeq(path + '')
if (!paths.length) {
throw new TypeError('undefined variable: ' + path)
}
var key = paths.shift()
var value = getValueFromScopes(key, scopes)
return paths.reduce(
(value, key) => {
if (_.isNil(value)) {
throw new TypeError('undefined variable: ' + key)
}
return getValueFromParent(key, value)
},
value
)
},
/*
* Parse property access sequence from access string
* @example
* accessSeq("foo.bar") // ['foo', 'bar']
* accessSeq("foo['bar']") // ['foo', 'bar']
* accessSeq("foo['b]r']") // ['foo', 'b]r']
* accessSeq("foo[bar.coo]") // ['foo', 'bar'], for bar.coo == 'bar'
*/
propertyAccessSeq: function (str) {
var seq = []
var name = ''
var j
var i = 0
while (i < str.length) {
switch (str[i]) {
case '[':
push()
var delemiter = str[i + 1]
if (/['"]/.test(delemiter)) { // foo["bar"]
j = str.indexOf(delemiter, i + 2)
assert(j !== -1, `unbalanced ${delemiter}: ${str}`)
name = str.slice(i + 2, j)
push()
i = j + 2
} else { // foo[bar.coo]
j = matchRightBracket(str, i + 1)
assert(j !== -1, `unbalanced []: ${str}`)
name = str.slice(i + 1, j)
if (!lexical.isInteger(name)) { // foo[bar] vs. foo[1]
name = this.get(name)
}
push()
i = j + 1
}
break
case '.':// foo.bar, foo[0].bar
push()
i++
break
default:// foo.bar
name += str[i]
i++
}
}
push()
return seq
function push () {
if (name.length) seq.push(name)
name = ''
}
}
}
exports.factory = function(ctx, opts) {
opts = _.assign({
strict_variables: false,
strict_filters: false,
blocks: {},
root: []
}, opts);
function setPropertyByPath (obj, path, val) {
var paths = (path + '').replace(/\[/g, '.').replace(/\]/g, '').split('.')
for (var i = 0; i < paths.length; i++) {
var key = paths[i]
if (i === paths.length - 1) {
return (obj[key] = val)
}
if (undefined === obj[key]) obj[key] = {}
// case for readonly objects
obj = obj[key] || {}
}
}
ctx = _.assign(ctx, {
liquid: opts
});
function getValueFromParent (key, value) {
return (key === 'size' && (_.isArray(value) || _.isString(value)))
? value.length
: value[key]
}
var scope = Object.create(Scope);
scope.opts = opts;
scope.scopes = [ctx];
return scope;
};
function getValueFromScopes (key, scopes) {
for (var i = scopes.length - 1; i > -1; i--) {
var scope = scopes[i]
if (scope.hasOwnProperty(key)) {
return scope[key]
}
}
throw new TypeError('undefined variable: ' + key)
}
function matchRightBracket (str, begin) {
var stack = 1 // count of '[' - count of ']'
for (var i = begin; i < str.length; i++) {
if (str[i] === '[') {
stack++
}
if (str[i] === ']') {
stack--
if (stack === 0) {
return i
}
}
}
return -1
}
exports.factory = function (ctx, opts) {
opts = _.assign({
strict_variables: false,
strict_filters: false,
blocks: {},
root: []
}, opts)
ctx = _.assign(ctx, {
liquid: opts
})
var scope = Object.create(Scope)
scope.opts = opts
scope.scopes = [ctx]
return scope
}
+41 -41
View File
@@ -1,56 +1,56 @@
const operators = require('./operators.js');
const lexical = require('./lexical.js');
const assert = require('../src/util/assert.js');
const operators = require('./operators.js')
const lexical = require('./lexical.js')
const assert = require('../src/util/assert.js')
function evalExp(exp, scope) {
assert(scope, 'unable to evalExp: scope undefined');
var operatorREs = lexical.operators,
match;
for (var i = 0; i < operatorREs.length; i++) {
var operatorRE = operatorREs[i];
var expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`);
if (match = exp.match(expRE)) {
var l = evalExp(match[1], scope);
var op = operators[match[2].trim()];
var r = evalExp(match[3], scope);
return op(l, r);
}
function evalExp (exp, scope) {
assert(scope, 'unable to evalExp: scope undefined')
var operatorREs = lexical.operators
var match
for (var i = 0; i < operatorREs.length; i++) {
var operatorRE = operatorREs[i]
var expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`)
if ((match = exp.match(expRE))) {
var l = evalExp(match[1], scope)
var op = operators[match[2].trim()]
var r = evalExp(match[3], scope)
return op(l, r)
}
}
if (match = exp.match(lexical.rangeLine)) {
var low = evalValue(match[1], scope),
high = evalValue(match[2], scope);
var range = [];
for (var j = low; j <= high; j++) {
range.push(j);
}
return range;
if ((match = exp.match(lexical.rangeLine))) {
var low = evalValue(match[1], scope)
var high = evalValue(match[2], scope)
var range = []
for (var j = low; j <= high; j++) {
range.push(j)
}
return range
}
return evalValue(exp, scope);
return evalValue(exp, scope)
}
function evalValue(str, scope) {
str = str && str.trim();
if (!str) return undefined;
function evalValue (str, scope) {
str = str && str.trim()
if (!str) return undefined
if (lexical.isLiteral(str)) {
return lexical.parseLiteral(str);
}
if (lexical.isVariable(str)) {
return scope.get(str);
}
if (lexical.isLiteral(str)) {
return lexical.parseLiteral(str)
}
if (lexical.isVariable(str)) {
return scope.get(str)
}
throw new TypeError(`cannot eval '${str}' as value`)
}
function isTruthy(val) {
if (val instanceof Array) return !!val.length;
return !!val;
function isTruthy (val) {
return !isFalsy(val)
}
function isFalsy(val) {
return !isTruthy(val);
function isFalsy (val) {
return val === false || undefined === val || val === null
}
module.exports = {
evalExp, evalValue, isTruthy, isFalsy
};
evalExp, evalValue, isTruthy, isFalsy
}
+54 -64
View File
@@ -1,73 +1,63 @@
const lexical = require('./lexical.js');
const _ = require('./util/underscore.js');
const Promise = require('any-promise');
const Syntax = require('./syntax.js');
const assert = require('./util/assert.js');
const lexical = require('./lexical.js')
const Promise = require('any-promise')
const Syntax = require('./syntax.js')
const assert = require('./util/assert.js')
function hash(markup, scope) {
var obj = {},
match;
lexical.hashCapture.lastIndex = 0;
while (match = lexical.hashCapture.exec(markup)) {
var k = match[1],
v = match[2];
obj[k] = Syntax.evalValue(v, scope);
}
return obj;
function hash (markup, scope) {
var obj = {}
var match
lexical.hashCapture.lastIndex = 0
while ((match = lexical.hashCapture.exec(markup))) {
var k = match[1]
var v = match[2]
obj[k] = Syntax.evalValue(v, scope)
}
return obj
}
module.exports = function() {
var tagImpls = {};
module.exports = function () {
var tagImpls = {}
var _tagInstance = {
render: function(scope) {
var obj = hash(this.token.args, scope);
var impl = this.tagImpl;
if (typeof impl.render !== 'function') {
return Promise.resolve('');
}
return Promise.resolve()
.then(() => typeof impl.render === 'function' ?
impl.render(scope, obj) : '')
.catch(function(e) {
if (_.isError(e)) {
throw e;
}
var msg = `Please reject with an Error in ${impl.render}, got ${e}`;
throw new Error(msg);
});
},
parse: function(token, tokens) {
this.type = 'tag';
this.token = token;
this.name = token.name;
var _tagInstance = {
render: function (scope) {
var obj = hash(this.token.args, scope)
var impl = this.tagImpl
if (typeof impl.render !== 'function') {
return Promise.resolve('')
}
return Promise.resolve().then(() => impl.render(scope, obj))
},
parse: function (token, tokens) {
this.type = 'tag'
this.token = token
this.name = token.name
var tagImpl = tagImpls[this.name];
assert(tagImpl, `tag ${this.name} not found`);
this.tagImpl = Object.create(tagImpl);
if (this.tagImpl.parse) {
this.tagImpl.parse(token, tokens);
}
}
};
function register(name, tag) {
tagImpls[name] = tag;
var tagImpl = tagImpls[this.name]
assert(tagImpl, `tag ${this.name} not found`)
this.tagImpl = Object.create(tagImpl)
if (this.tagImpl.parse) {
this.tagImpl.parse(token, tokens)
}
}
}
function construct(token, tokens) {
var instance = Object.create(_tagInstance);
instance.parse(token, tokens);
return instance;
}
function register (name, tag) {
tagImpls[name] = tag
}
function clear() {
tagImpls = {};
}
function construct (token, tokens) {
var instance = Object.create(_tagInstance)
instance.parse(token, tokens)
return instance
}
return {
construct,
register,
clear
};
};
function clear () {
tagImpls = {}
}
return {
construct,
register,
clear
}
}
+85 -62
View File
@@ -1,73 +1,96 @@
const lexical = require('./lexical.js');
const TokenizationError = require('./util/error.js').TokenizationError;
const _ = require('./util/underscore.js');
const assert = require('../src/util/assert.js');
const lexical = require('./lexical.js')
const TokenizationError = require('./util/error.js').TokenizationError
const _ = require('./util/underscore.js')
const assert = require('../src/util/assert.js')
function parse(html) {
assert(_.isString(html), 'illegal input type');
function parse (html, filepath, options) {
assert(_.isString(html), 'illegal input type')
var tokens = [];
var syntax = /({%(.*?)%})|({{(.*?)}})/g;
var result, htmlFragment, token;
var lastMatchEnd = 0, lastMatchBegin = -1, parsedLinesCount = 0;
html = whiteSpaceCtrl(html, options)
while ((result = syntax.exec(html)) !== null) {
// passed html fragments
if (result.index > lastMatchEnd) {
htmlFragment = html.slice(lastMatchEnd, result.index);
tokens.push({
type: 'html',
raw: htmlFragment,
value: htmlFragment
});
}
// tag appeared
if (result[1]) {
token = factory('tag', 1, result);
var tokens = []
var syntax = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
var result, htmlFragment, token
var lastMatchEnd = 0
var lastMatchBegin = -1
var parsedLinesCount = 0
var match = token.value.match(lexical.tagLine);
if (!match) {
throw new TokenizationError(`illegal tag syntax`, token);
}
token.name = match[1];
token.args = match[2];
tokens.push(token);
}
// output
else { token = factory('output', 3, result);
tokens.push(token);
}
lastMatchEnd = syntax.lastIndex;
while ((result = syntax.exec(html)) !== null) {
// passed html fragments
if (result.index > lastMatchEnd) {
htmlFragment = html.slice(lastMatchEnd, result.index)
tokens.push({
type: 'html',
raw: htmlFragment,
value: htmlFragment
})
}
if (result[1]) {
// tag appeared
token = factory('tag', 1, result)
// remaining html
if (html.length > lastMatchEnd) {
htmlFragment = html.slice(lastMatchEnd, html.length);
tokens.push({
type: 'html',
raw: htmlFragment,
value: htmlFragment
});
}
return tokens;
var match = token.value.match(lexical.tagLine)
if (!match) {
throw new TokenizationError(`illegal tag syntax`, token)
}
token.name = match[1]
token.args = match[2]
function factory(type, offset, match) {
return {
type: type,
raw: match[offset],
value: match[offset + 1].trim(),
line: getLineNum(match),
input: html
};
}
// get last line indentation
var lineStart = (htmlFragment || '').split('\n')
token.indent = lineStart[lineStart.length - 1].length
function getLineNum(match) {
var lines = match.input.slice(lastMatchBegin + 1, match.index).split('\n');
parsedLinesCount += lines.length - 1;
lastMatchBegin = match.index;
return parsedLinesCount + 1;
tokens.push(token)
} else {
// output
token = factory('output', 3, result)
tokens.push(token)
}
lastMatchEnd = syntax.lastIndex
}
// remaining html
if (html.length > lastMatchEnd) {
htmlFragment = html.slice(lastMatchEnd, html.length)
tokens.push({
type: 'html',
raw: htmlFragment,
value: htmlFragment
})
}
return tokens
function factory (type, offset, match) {
return {
type: type,
raw: match[offset],
value: match[offset + 1].trim(),
line: getLineNum(match),
input: html,
file: filepath
}
}
function getLineNum (match) {
var lines = match.input.slice(lastMatchBegin + 1, match.index).split('\n')
parsedLinesCount += lines.length - 1
lastMatchBegin = match.index
return parsedLinesCount + 1
}
}
exports.parse = parse;
function whiteSpaceCtrl (html, options) {
options = options || {}
if (options.trim_left) {
html = html.replace(/({[{%])-?/g, '$1-')
}
if (options.trim_right) {
html = html.replace(/-?([%}]})/g, '-$1')
}
var rLeft = options.greedy ? /\s+({[{%]-)/g : /[\t\r ]*({[{%]-)/g
var rRight = options.greedy ? /(-[%}]})\s+/g : /(-[%}]})[\t\r ]*\n?/g
return html.replace(rLeft, '$1').replace(rRight, '$1')
}
exports.parse = parse
exports.whiteSpaceCtrl = whiteSpaceCtrl
+7 -10
View File
@@ -1,13 +1,10 @@
const AssertionError = require('./error.js').AssertionError;
const AssertionError = require('./error.js').AssertionError
function assert(predicate, message) {
if (!predicate) {
if (message instanceof Error) {
throw message;
}
var message = message || `expect ${predicate} to be true`;
throw new AssertionError(message);
}
function assert (predicate, message) {
if (!predicate) {
message = message || `expect ${predicate} to be true`
throw new AssertionError(message)
}
}
module.exports = assert;
module.exports = assert
+100 -92
View File
@@ -1,98 +1,106 @@
const _ = require('./underscore.js');
const _ = require('./underscore.js')
function TokenizationError(message, token) {
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = this.constructor.name;
this.input = token.input;
this.line = token.line;
var context = mkContext(token.input, token.line);
this.message = message + ', line:' + token.line;
this.stack = context + '\n' + (this.stack || '');
}
TokenizationError.prototype = Object.create(Error.prototype);
TokenizationError.prototype.constructor = TokenizationError;
function ParseError(e, token) {
this.name = this.constructor.name;
this.stack = e.stack;
this.input = token.input;
this.line = token.line;
var context = mkContext(token.input, token.line);
this.message = e.message + ', line:' + token.line;
this.stack = context + '\n' + (this.stack || '');
}
ParseError.prototype = Object.create(Error.prototype);
ParseError.prototype.constructor = ParseError;
function RenderError(e, tpl) {
this.name = this.constructor.name;
this.stack = e.stack;
this.input = tpl.token.input;
this.line = tpl.token.line;
var context = mkContext(tpl.token.input, tpl.token.line);
this.message = e.message + ', line:' + tpl.token.line;
this.stack = context + '\n' + (e.stack || '');
}
RenderError.prototype = Object.create(Error.prototype);
RenderError.prototype.constructor = RenderError;
function RenderBreakError(message) {
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = this.constructor.name;
this.message = message || '';
}
RenderBreakError.prototype = Object.create(Error.prototype);
RenderBreakError.prototype.constructor = RenderBreakError;
function AssertionError(message) {
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = this.constructor.name;
this.message = message;
}
AssertionError.prototype = Object.create(Error.prototype);
AssertionError.prototype.constructor = AssertionError;
function mkContext(input, line) {
var lines = input.split('\n');
var begin = Math.max(line - 2, 1);
var end = Math.min(line + 3, lines.length);
var context = _
.range(begin, end + 1)
.map(l => [
(l === line) ? '>> ' : ' ',
align(l, end),
'| ',
lines[l - 1]
].join(''))
.join('\n');
return context;
function initError () {
this.name = this.constructor.name
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor)
}
}
function align(n, max) {
var length = (max + '').length;
var str = n + '';
var blank = Array(length - str.length).join(' ');
return blank + str;
function initLiquidError (message, token) {
initError.call(this)
this.input = token.input
this.line = token.line
this.file = token.file
var context = mkContext(token.input, token.line)
this.message = mkMessage(message, token)
this.stack = context + '\n' + (this.stack || this.message)
}
function TokenizationError (message, token) {
initLiquidError.call(this, message, token)
}
TokenizationError.prototype = Object.create(Error.prototype)
TokenizationError.prototype.constructor = TokenizationError
function ParseError (e, token) {
_.assign(this, e)
this.originalError = e
initLiquidError.call(this, e.message, token)
}
ParseError.prototype = Object.create(Error.prototype)
ParseError.prototype.constructor = ParseError
function RenderError (e, tpl) {
// return the original render error
if (e instanceof RenderError) {
return e
}
_.assign(this, e)
this.originalError = e
initLiquidError.call(this, e.message, tpl.token)
}
RenderError.prototype = Object.create(Error.prototype)
RenderError.prototype.constructor = RenderError
function RenderBreakError (message) {
initError.call(this)
this.message = message + ''
}
RenderBreakError.prototype = Object.create(Error.prototype)
RenderBreakError.prototype.constructor = RenderBreakError
function AssertionError (message) {
initError.call(this)
this.message = message + ''
}
AssertionError.prototype = Object.create(Error.prototype)
AssertionError.prototype.constructor = AssertionError
function mkContext (input, line) {
var lines = input.split('\n')
var begin = Math.max(line - 2, 1)
var end = Math.min(line + 3, lines.length)
var context = _
.range(begin, end + 1)
.map(l => [
(l === line) ? '>> ' : ' ',
align(l, end),
'| ',
lines[l - 1]
].join(''))
.join('\n')
return context
}
function align (n, max) {
var length = (max + '').length
var str = n + ''
var blank = Array(length - str.length).join(' ')
return blank + str
}
function mkMessage (msg, token) {
msg = msg || ''
if (token.file) {
msg += ', file:' + token.file
}
if (token.line) {
msg += ', line:' + token.line
}
return msg
}
module.exports = {
TokenizationError,
ParseError,
RenderBreakError,
AssertionError,
RenderError
};
TokenizationError,
ParseError,
RenderBreakError,
AssertionError,
RenderError
}
+14 -14
View File
@@ -1,20 +1,20 @@
const fs = require('fs');
const fs = require('fs')
function readFileAsync(filepath) {
return new Promise(function(resolve, reject) {
fs.readFile(filepath, 'utf8', function(err, content) {
err ? reject(err) : resolve(content);
});
});
function readFileAsync (filepath) {
return new Promise(function (resolve, reject) {
fs.readFile(filepath, 'utf8', function (err, content) {
err ? reject(err) : resolve(content)
})
})
};
function statFileAsync(path) {
return new Promise(function(resolve, reject) {
fs.stat(path, (err, stat) => err ? reject(err) : resolve(stat))
});
function statFileAsync (path) {
return new Promise(function (resolve, reject) {
fs.stat(path, (err, stat) => err ? reject(err) : resolve(stat))
})
};
module.exports = {
readFileAsync,
statFileAsync
};
readFileAsync,
statFileAsync
}
+20 -20
View File
@@ -1,35 +1,35 @@
const Promise = require('any-promise');
const Promise = require('any-promise')
/*
* Call functions in serial until someone resolved.
* @param {Array} iterable the array to iterate with.
* @param {Array} iteratee returns a new promise.
* The iteratee is invoked with three arguments: (value, index, iterable).
* The iteratee is invoked with three arguments: (value, index, iterable).
*/
function anySeries(iterable, iteratee) {
var ret = Promise.reject(new Error('init'));
iterable.forEach(function(item, idx) {
ret = ret.catch(e => iteratee(item, idx, iterable));
});
return ret;
function anySeries (iterable, iteratee) {
var ret = Promise.reject(new Error('init'))
iterable.forEach(function (item, idx) {
ret = ret.catch(e => iteratee(item, idx, iterable))
})
return ret
}
/*
* Call functions in serial until someone rejected.
* @param {Array} iterable the array to iterate with.
* @param {Array} iteratee returns a new promise.
* The iteratee is invoked with three arguments: (value, index, iterable).
* The iteratee is invoked with three arguments: (value, index, iterable).
*/
function mapSeries(iterable, iteratee) {
var ret = Promise.resolve('init');
var result = [];
iterable.forEach(function(item, idx) {
ret = ret
.then(() => iteratee(item, idx, iterable))
.then(x => result.push(x));
});
return ret.then(() => result);
function mapSeries (iterable, iteratee) {
var ret = Promise.resolve('init')
var result = []
iterable.forEach(function (item, idx) {
ret = ret
.then(() => iteratee(item, idx, iterable))
.then(x => result.push(x))
})
return ret.then(() => result)
}
exports.anySeries = anySeries;
exports.mapSeries = mapSeries;
exports.anySeries = anySeries
exports.mapSeries = mapSeries
+181 -181
View File
@@ -1,200 +1,200 @@
var monthNames = [
"January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"
];
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'
]
var monthNamesShort = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
"Nov", "Dec"
];
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
'Nov', 'Dec'
]
var dayNames = [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
];
var dayNamesShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
]
var dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
var suffixes = {
1: 'st',
2: 'nd',
3: 'rd',
'default': 'th'
};
1: 'st',
2: 'nd',
3: 'rd',
'default': 'th'
}
// prototype extensions
var _date = {
daysInMonth: function(d) {
var feb = _date.isLeapYear(d) ? 29 : 28;
return [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
},
daysInMonth: function (d) {
var feb = _date.isLeapYear(d) ? 29 : 28
return [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
},
getDayOfYear: function(d) {
var num = 0;
for (var i = 0; i < d.getMonth(); ++i) {
num += _date.daysInMonth(d)[i];
}
return num + d.getDate();
},
// Startday is an integer of which day to start the week measuring from
// TODO: that comment was retarted. fix it.
getWeekOfYear: function(d, startDay) {
// Skip to startDay of this week
var now = this.getDayOfYear(d) + (startDay - d.getDay());
// Find the first startDay of the year
var jan1 = new Date(d.getFullYear(), 0, 1);
var then = (7 - jan1.getDay() + startDay);
return _number.pad(Math.floor((now - then) / 7) + 1, 2);
},
isLeapYear: function(d) {
var year = d.getFullYear();
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)));
},
getSuffix: function(d) {
var str = d.getDate().toString();
var index = parseInt(str.slice(-1));
return suffixes[index] || suffixes['default'];
},
century: function(d) {
return parseInt(d.getFullYear().toString().substring(0, 2), 10);
getDayOfYear: function (d) {
var num = 0
for (var i = 0; i < d.getMonth(); ++i) {
num += _date.daysInMonth(d)[i]
}
};
return num + d.getDate()
},
// Startday is an integer of which day to start the week measuring from
// TODO: that comment was retarted. fix it.
getWeekOfYear: function (d, startDay) {
// Skip to startDay of this week
var now = this.getDayOfYear(d) + (startDay - d.getDay())
// Find the first startDay of the year
var jan1 = new Date(d.getFullYear(), 0, 1)
var then = (7 - jan1.getDay() + startDay)
return _number.pad(Math.floor((now - then) / 7) + 1, 2)
},
isLeapYear: function (d) {
var year = d.getFullYear()
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)))
},
getSuffix: function (d) {
var str = d.getDate().toString()
var index = parseInt(str.slice(-1))
return suffixes[index] || suffixes['default']
},
century: function (d) {
return parseInt(d.getFullYear().toString().substring(0, 2), 10)
}
}
var _number = {
pad: function(value, size, ch) {
if (!ch) ch = '0';
var result = value.toString();
var pad = size - result.length;
pad: function (value, size, ch) {
if (!ch) ch = '0'
var result = value.toString()
var pad = size - result.length
while (pad-- > 0) {
result = ch + result;
}
return result;
while (pad-- > 0) {
result = ch + result
}
};
return result
}
}
var format_codes = {
a: function(d) {
return dayNamesShort[d.getDay()];
},
A: function(d) {
return dayNames[d.getDay()];
},
b: function(d) {
return monthNamesShort[d.getMonth()];
},
B: function(d) {
return monthNames[d.getMonth()];
},
c: function(d) {
return d.toLocaleString();
},
C: function(d) {
return _date.century(d);
},
d: function(d) {
return _number.pad(d.getDate(), 2);
},
e: function(d) {
return _number.pad(d.getDate(), 2, ' ');
},
H: function(d) {
return _number.pad(d.getHours(), 2);
},
I: function(d) {
return _number.pad(d.getHours() % 12 || 12, 2);
},
j: function(d) {
return _number.pad(_date.getDayOfYear(d), 3);
},
k: function(d) {
return _number.pad(d.getHours(), 2, ' ');
},
l: function(d) {
return _number.pad(d.getHours() % 12 || 12, 2, ' ');
},
L: function(d) {
return _number.pad(d.getMilliseconds(), 3);
},
m: function(d) {
return _number.pad(d.getMonth() + 1, 2);
},
M: function(d) {
return _number.pad(d.getMinutes(), 2);
},
p: function(d) {
return (d.getHours() < 12 ? 'AM' : 'PM');
},
P: function(d) {
return (d.getHours() < 12 ? 'am' : 'pm');
},
q: function(d) {
return _date.getSuffix(d);
},
s: function(d) {
return Math.round(d.valueOf() / 1000);
},
S: function(d) {
return _number.pad(d.getSeconds(), 2);
},
u: function(d) {
return d.getDay() || 7;
},
U: function(d) {
return _date.getWeekOfYear(d, 0);
},
w: function(d) {
return d.getDay();
},
W: function(d) {
return _date.getWeekOfYear(d, 1);
},
x: function(d) {
return d.toLocaleDateString();
},
X: function(d) {
return d.toLocaleTimeString();
},
y: function(d) {
return d.getFullYear().toString().substring(2, 4);
},
Y: function(d) {
return d.getFullYear();
},
z: function(d) {
var tz = d.getTimezoneOffset() / 60 * 100;
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4);
},
"%": function() {
return '%';
var formatCodes = {
a: function (d) {
return dayNamesShort[d.getDay()]
},
A: function (d) {
return dayNames[d.getDay()]
},
b: function (d) {
return monthNamesShort[d.getMonth()]
},
B: function (d) {
return monthNames[d.getMonth()]
},
c: function (d) {
return d.toLocaleString()
},
C: function (d) {
return _date.century(d)
},
d: function (d) {
return _number.pad(d.getDate(), 2)
},
e: function (d) {
return _number.pad(d.getDate(), 2, ' ')
},
H: function (d) {
return _number.pad(d.getHours(), 2)
},
I: function (d) {
return _number.pad(d.getHours() % 12 || 12, 2)
},
j: function (d) {
return _number.pad(_date.getDayOfYear(d), 3)
},
k: function (d) {
return _number.pad(d.getHours(), 2, ' ')
},
l: function (d) {
return _number.pad(d.getHours() % 12 || 12, 2, ' ')
},
L: function (d) {
return _number.pad(d.getMilliseconds(), 3)
},
m: function (d) {
return _number.pad(d.getMonth() + 1, 2)
},
M: function (d) {
return _number.pad(d.getMinutes(), 2)
},
p: function (d) {
return (d.getHours() < 12 ? 'AM' : 'PM')
},
P: function (d) {
return (d.getHours() < 12 ? 'am' : 'pm')
},
q: function (d) {
return _date.getSuffix(d)
},
s: function (d) {
return Math.round(d.valueOf() / 1000)
},
S: function (d) {
return _number.pad(d.getSeconds(), 2)
},
u: function (d) {
return d.getDay() || 7
},
U: function (d) {
return _date.getWeekOfYear(d, 0)
},
w: function (d) {
return d.getDay()
},
W: function (d) {
return _date.getWeekOfYear(d, 1)
},
x: function (d) {
return d.toLocaleDateString()
},
X: function (d) {
return d.toLocaleTimeString()
},
y: function (d) {
return d.getFullYear().toString().substring(2, 4)
},
Y: function (d) {
return d.getFullYear()
},
z: function (d) {
var tz = d.getTimezoneOffset() / 60 * 100
console.log('tz', tz)
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4)
},
'%': function () {
return '%'
}
}
formatCodes.h = formatCodes.b
formatCodes.N = formatCodes.L
var strftime = function (d, format) {
var output = ''
var remaining = format
while (true) {
var r = /%./g
var results = r.exec(remaining)
// No more format codes. Add the remaining text and return
if (!results) {
return output + remaining
}
};
format_codes.h = format_codes.b;
format_codes.N = format_codes.L;
var strftime = function(d, format) {
var output = '';
var remaining = format;
// Add the preceding text
output += remaining.slice(0, r.lastIndex - 2)
remaining = remaining.slice(r.lastIndex)
while (true) {
var r = /%./g;
var results = r.exec(remaining);
// Add the format code
var ch = results[0].charAt(1)
var func = formatCodes[ch]
output += func ? func.call(this, d) : '%' + ch
}
}
// No more format codes. Add the remaining text and return
if (!results) {
return output + remaining;
}
// Add the preceding text
output += remaining.slice(0, r.lastIndex - 2);
remaining = remaining.slice(r.lastIndex);
// Add the format code
var ch = results[0].charAt(1);
var func = format_codes[ch];
output += func ? func.call(this, d) : '%' + ch;
}
};
module.exports = strftime;
module.exports = strftime
+87 -80
View File
@@ -1,41 +1,52 @@
const toStr = Object.prototype.toString
/*
* Checks if value is classified as a String primitive or object.
* @param {any} value The value to check.
* @return {Boolean} Returns true if value is a string, else false.
*/
function isString(value) {
return value instanceof String || typeof value === 'string';
function isString (value) {
return value instanceof String || typeof value === 'string'
}
function isError(value) {
var signature = Object.prototype.toString.call(value);
// [object XXXError]
return signature.substr(-6, 5) === 'Error' ||
(typeof value.message == 'string' && typeof value.name == 'string');
function isNil (value) {
return value === null || value === undefined
}
function isArray (value) {
// be compatible with IE 8
return toStr.call(value) === '[object Array]'
}
function isError (value) {
var signature = Object.prototype.toString.call(value)
// [object XXXError]
return signature.substr(-6, 5) === 'Error' ||
(typeof value.message === 'string' && typeof value.name === 'string')
}
/*
* Iterates over own enumerable string keyed properties of an object and invokes iteratee for each property.
* The iteratee is invoked with three arguments: (value, key, object).
* Iterates over own enumerable string keyed properties of an object and invokes iteratee for each property.
* The iteratee is invoked with three arguments: (value, key, object).
* Iteratee functions may exit iteration early by explicitly returning false.
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @return {Object} Returns object.
*/
function forOwn(object, iteratee) {
object = object || {};
for (var k in object) {
if (object.hasOwnProperty(k)) {
if (iteratee(object[k], k, object) === false) break;
}
function forOwn (object, iteratee) {
object = object || {}
for (var k in object) {
if (object.hasOwnProperty(k)) {
if (iteratee(object[k], k, object) === false) break
}
return object;
}
return object
}
/*
* Assigns own enumerable string keyed properties of source objects to the destination object.
* Source objects are applied from left to right.
* Subsequent sources overwrite property assignments of previous sources.
* Assigns own enumerable string keyed properties of source objects to the destination object.
* Source objects are applied from left to right.
* Subsequent sources overwrite property assignments of previous sources.
*
* Note: This method mutates object and is loosely based on Object.assign.
*
@@ -43,89 +54,85 @@ function forOwn(object, iteratee) {
* @param {...Object} sources The source objects.
* @return {Object} Returns object.
*/
function assign(object) {
object = isObject(object) ? object : {};
var srcs = Array.prototype.slice.call(arguments, 1);
srcs.forEach(function(src) {
_assignBinary(object, src);
});
return object;
function assign (object) {
object = isObject(object) ? object : {}
var srcs = Array.prototype.slice.call(arguments, 1)
srcs.forEach(function (src) {
_assignBinary(object, src)
})
return object
}
function _assignBinary(dst, src) {
if (!dst) return dst;
forOwn(src, function(v, k) {
dst[k] = v;
});
return dst;
function _assignBinary (dst, src) {
forOwn(src, function (v, k) {
dst[k] = v
})
return dst
}
function isArray(value) {
return value instanceof Array;
function echo (prefix) {
return v => {
console.log('[' + prefix + ']', v)
return v
}
}
function echo(prefix) {
return v => {
console.log('[' + prefix + ']', v);
return v;
};
}
function uniq(arr) {
var u = {},
a = [];
for (var i = 0, l = arr.length; i < l; ++i) {
if (u.hasOwnProperty(arr[i])) {
continue;
}
a.push(arr[i]);
u[arr[i]] = 1;
function uniq (arr) {
var u = {}
var a = []
for (var i = 0, l = arr.length; i < l; ++i) {
if (u.hasOwnProperty(arr[i])) {
continue
}
return a;
a.push(arr[i])
u[arr[i]] = 1
}
return a
}
/*
* Checks if value is the language type of Object.
* Checks if value is the language type of Object.
* (e.g. arrays, functions, objects, regexes, new Number(0), and new String(''))
* @param {any} value The value to check.
* @return {Boolean} Returns true if value is an object, else false.
*/
function isObject(value) {
return value !== null && typeof value === 'object';
function isObject (value) {
var type = typeof value
return value != null && (type === 'object' || type === 'function')
}
/*
* A function to create flexibly-numbered lists of integers,
* handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1.
* Returns a list of integers from start (inclusive) to stop (exclusive),
* incremented (or decremented) by step, exclusive.
* Note that ranges that stop before they start are considered to be zero-length instead of
* A function to create flexibly-numbered lists of integers,
* handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1.
* Returns a list of integers from start (inclusive) to stop (exclusive),
* incremented (or decremented) by step, exclusive.
* Note that ranges that stop before they start are considered to be zero-length instead of
* negative if you'd like a negative range, use a negative step.
*/
function range(start, stop, step) {
if (arguments.length === 1) {
stop = start;
start = 0;
}
step = step || 1;
function range (start, stop, step) {
if (arguments.length === 1) {
stop = start
start = 0
}
step = step || 1
var arr = [];
for (var i = start; i < stop; i += step) {
arr.push(i);
}
return arr;
var arr = []
for (var i = start; i < stop; i += step) {
arr.push(i)
}
return arr
}
exports.isString = isString;
exports.isArray = isArray;
exports.isObject = isObject;
exports.isError = isError;
exports.isString = isString
exports.isObject = isObject
exports.isArray = isArray
exports.isNil = isNil
exports.isError = isError
exports.range = range;
exports.range = range
exports.forOwn = forOwn;
exports.assign = assign;
exports.uniq = uniq;
exports.forOwn = forOwn
exports.assign = assign
exports.uniq = uniq
exports.echo = echo;
exports.echo = echo
+19 -21
View File
@@ -1,22 +1,20 @@
const Liquid = require('..');
const lexical = Liquid.lexical;
const Promise = require('any-promise');
const re = new RegExp(`(${lexical.identifier.source})\\s*=(.*)`);
const assert = require('../src/util/assert.js');
const Liquid = require('..')
const lexical = Liquid.lexical
const Promise = require('any-promise')
const re = new RegExp(`(${lexical.identifier.source})\\s*=(.*)`)
const assert = require('../src/util/assert.js')
module.exports = function(liquid) {
liquid.registerTag('assign', {
parse: function(token){
var match = token.args.match(re);
assert(match, `illegal token ${token.raw}`);
this.key = match[1];
this.value = match[2];
},
render: function(scope) {
scope.set(this.key, liquid.evalOutput(this.value, scope));
return Promise.resolve('');
}
});
};
module.exports = function (liquid) {
liquid.registerTag('assign', {
parse: function (token) {
var match = token.args.match(re)
assert(match, `illegal token ${token.raw}`)
this.key = match[1]
this.value = match[2]
},
render: function (scope) {
scope.set(this.key, liquid.evalOutput(this.value, scope))
return Promise.resolve('')
}
})
}
+35 -39
View File
@@ -1,45 +1,41 @@
const Liquid = require('..');
const assert = require('../src/util/assert.js');
const Liquid = require('..')
module.exports = function(liquid) {
liquid.registerTag('case', {
module.exports = function (liquid) {
liquid.registerTag('case', {
parse: function(tagToken, remainTokens) {
this.cond = tagToken.args;
this.cases = [];
this.elseTemplates = [];
parse: function (tagToken, remainTokens) {
this.cond = tagToken.args
this.cases = []
this.elseTemplates = []
var p = [],
stream = liquid.parser.parseStream(remainTokens)
.on('tag:when', token => {
if (!this.cases[token.args]) {
this.cases.push({
val: token.args,
templates: p = []
});
}
})
.on('tag:else', token => p = this.elseTemplates)
.on('tag:endcase', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`);
});
var p = []
var stream = liquid.parser.parseStream(remainTokens)
.on('tag:when', token => {
this.cases.push({
val: token.args,
templates: p = []
})
})
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endcase', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start();
},
stream.start()
},
render: function(scope, hash) {
for (var i = 0; i < this.cases.length; i++) {
var branch = this.cases[i];
var val = Liquid.evalExp(branch.val, scope);
var cond = Liquid.evalExp(this.cond, scope);
if (val === cond) {
return liquid.renderer.renderTemplates(branch.templates, scope);
}
}
return liquid.renderer.renderTemplates(this.elseTemplates, scope);
render: function (scope, hash) {
for (var i = 0; i < this.cases.length; i++) {
var branch = this.cases[i]
var val = Liquid.evalExp(branch.val, scope)
var cond = Liquid.evalExp(this.cond, scope)
if (val === cond) {
return liquid.renderer.renderTemplates(branch.templates, scope)
}
});
};
}
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
})
}
+86 -77
View File
@@ -1,88 +1,97 @@
const Liquid = require('..');
const lexical = Liquid.lexical;
const mapSeries = require('../src/util/promise.js').mapSeries;
const RenderBreakError = Liquid.Types.RenderBreakError;
const assert = require('../src/util/assert.js');
const Liquid = require('..')
const lexical = Liquid.lexical
const mapSeries = require('../src/util/promise.js').mapSeries
const _ = require('../src/util/underscore.js')
const RenderBreakError = Liquid.Types.RenderBreakError
const assert = require('../src/util/assert.js')
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
`(${lexical.value.source})` +
`(?:\\s+${lexical.hash.source})*` +
`(?:\\s+(reversed))?$`);
`(?:\\s+(reversed))?` +
`(?:\\s+${lexical.hash.source})*$`)
module.exports = function(liquid) {
liquid.registerTag('for', {
module.exports = function (liquid) {
liquid.registerTag('for', {
parse: function(tagToken, remainTokens) {
var match = re.exec(tagToken.args);
assert(match, `illegal tag: ${tagToken.raw}`);
this.variable = match[1];
this.collection = match[2];
this.reversed = !!match[3];
parse: function (tagToken, remainTokens) {
var match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1]
this.collection = match[2]
this.reversed = !!match[3]
this.templates = [];
this.elseTemplates = [];
this.templates = []
this.elseTemplates = []
var p, stream = liquid.parser.parseStream(remainTokens)
.on('start', () => p = this.templates)
.on('tag:else', () => p = this.elseTemplates)
.on('tag:endfor', () => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`);
});
var p
var stream = liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates))
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endfor', () => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start();
},
stream.start()
},
render: function(scope, hash) {
var collection = Liquid.evalExp(this.collection, scope);
if (Liquid.isFalsy(collection)) {
return liquid.renderer.renderTemplates(this.elseTemplates, scope);
}
render: function (scope, hash) {
var collection = Liquid.evalExp(this.collection, scope)
var length = collection.length;
var offset = hash.offset || 0;
var limit = (hash.limit === undefined) ? collection.length : hash.limit;
collection = collection.slice(offset, offset + limit);
if (this.reversed) collection.reverse();
var contexts = collection.map((item, i) => {
var ctx = {};
ctx[this.variable] = item;
ctx.forloop = {
first: i === 0,
index: i + 1,
index0: i,
last: i === length - 1,
length: length,
rindex: length - i,
rindex0: length - i - 1,
stop: false,
skip: false
};
return ctx;
});
var html = '';
return mapSeries(contexts, (context) => {
scope.push(context);
return liquid.renderer
.renderTemplates(this.templates, scope)
.then(partial => html += partial)
.catch(e => {
if (e instanceof RenderBreakError) {
html += e.resolvedHTML;
if (e.message === 'continue') return;
}
throw e;
})
.then(() => scope.pop());
}).catch((e) => {
if (e instanceof RenderBreakError && e.message === 'break') {
return;
}
throw e;
}).then(() => html);
if (!Array.isArray(collection)) {
if (_.isString(collection) && collection.length > 0) {
collection = [collection]
} else if (_.isObject(collection)) {
collection = Object.keys(collection).map((key) => [key, collection[key]])
}
});
};
}
if (!Array.isArray(collection) || !collection.length) {
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
var length = collection.length
var offset = hash.offset || 0
var limit = (hash.limit === undefined) ? collection.length : hash.limit
collection = collection.slice(offset, offset + limit)
if (this.reversed) collection.reverse()
var contexts = collection.map((item, i) => {
var ctx = {}
ctx[this.variable] = item
ctx.forloop = {
first: i === 0,
index: i + 1,
index0: i,
last: i === length - 1,
length: length,
rindex: length - i,
rindex0: length - i - 1
}
return ctx
})
var html = ''
return mapSeries(contexts, (context) => {
return Promise.resolve()
.then(() => scope.push(context))
.then(() => liquid.renderer.renderTemplates(this.templates, scope))
.then(partial => (html += partial))
.catch(e => {
if (e instanceof RenderBreakError) {
html += e.resolvedHTML
if (e.message === 'continue') return
}
throw e
})
.then(() => scope.pop())
}).catch((e) => {
if (e instanceof RenderBreakError && e.message === 'break') {
return
}
throw e
}).then(() => html)
}
})
}
+37 -40
View File
@@ -1,46 +1,43 @@
const Liquid = require('..');
const Liquid = require('..')
module.exports = function(liquid) {
liquid.registerTag('if', {
module.exports = function (liquid) {
liquid.registerTag('if', {
parse: function(tagToken, remainTokens) {
parse: function (tagToken, remainTokens) {
this.branches = []
this.elseTemplates = []
this.branches = [];
this.elseTemplates = [];
var p
var stream = liquid.parser.parseStream(remainTokens)
.on('start', () => this.branches.push({
cond: tagToken.args,
templates: (p = [])
}))
.on('tag:elsif', token => {
this.branches.push({
cond: token.args,
templates: p = []
})
})
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endif', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
var p, stream = liquid.parser.parseStream(remainTokens)
.on('start', x => this.branches.push({
cond: tagToken.args,
templates: p = []
}))
.on('tag:elsif', token => {
if (!this.branches[token.args]) {
this.branches.push({
cond: token.args,
templates: p = []
});
}
})
.on('tag:else', token => p = this.elseTemplates)
.on('tag:endif', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`);
});
stream.start()
},
stream.start();
},
render: function(scope, hash) {
for (var i = 0; i < this.branches.length; i++) {
var branch = this.branches[i];
var cond = Liquid.evalExp(branch.cond, scope);
if (Liquid.isTruthy(cond)) {
return liquid.renderer.renderTemplates(branch.templates, scope);
}
}
return liquid.renderer.renderTemplates(this.elseTemplates, scope);
render: function (scope, hash) {
for (var i = 0; i < this.branches.length; i++) {
var branch = this.branches[i]
var cond = Liquid.evalExp(branch.cond, scope)
if (Liquid.isTruthy(cond)) {
return liquid.renderer.renderTemplates(branch.templates, scope)
}
});
};
}
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
})
}
+36 -38
View File
@@ -1,42 +1,40 @@
const Liquid = require('..');
const lexical = Liquid.lexical;
const withRE = new RegExp(`with\\s+(${lexical.value.source})`);
const assert = require('../src/util/assert.js');
const Liquid = require('..')
const lexical = Liquid.lexical
const withRE = new RegExp(`with\\s+(${lexical.value.source})`)
const assert = require('../src/util/assert.js')
module.exports = function(liquid) {
module.exports = function (liquid) {
liquid.registerTag('include', {
parse: function (token) {
var match = lexical.value.exec(token.args)
assert(match, `illegal token ${token.raw}`)
this.value = match[0]
liquid.registerTag('include', {
parse: function(token){
var match = lexical.value.exec(token.args);
assert(match, `illegal token ${token.raw}`);
this.value = match[0];
match = withRE.exec(token.args)
if (match) {
this.with = match[1]
}
},
render: function (scope, hash) {
var filepath = Liquid.evalValue(this.value, scope)
match = withRE.exec(token.args);
if(match){
this.with = match[1];
}
},
render: function(scope, hash) {
var filepath = Liquid.evalValue(this.value, scope);
var register = scope.get('liquid')
var originBlocks = register.blocks
register.blocks = {}
var register = scope.get('liquid');
var originBlocks = register.blocks;
register.blocks = {};
if(this.with){
hash[filepath] = Liquid.evalValue(this.with, scope);
}
return liquid.getTemplate(filepath, register.root)
.then((templates) => {
scope.push(hash);
return liquid.renderer.renderTemplates(templates, scope);
})
.then((html) => {
scope.pop();
register.blocks = originBlocks;
return html;
});
}
});
};
if (this.with) {
hash[filepath] = Liquid.evalValue(this.with, scope)
}
return liquid.getTemplate(filepath, register.root)
.then((templates) => {
scope.push(hash)
return liquid.renderer.renderTemplates(templates, scope)
})
.then((html) => {
scope.pop()
register.blocks = originBlocks
return html
})
}
})
}
+63 -61
View File
@@ -1,66 +1,68 @@
const Liquid = require('..');
const Promise = require('any-promise');
const lexical = Liquid.lexical;
const assert = require('../src/util/assert.js');
const Liquid = require('..')
const Promise = require('any-promise')
const lexical = Liquid.lexical
const assert = require('../src/util/assert.js')
module.exports = function(liquid) {
module.exports = function (liquid) {
liquid.registerTag('layout', {
parse: function (token, remainTokens) {
var match = lexical.value.exec(token.args)
assert(match, `illegal token ${token.raw}`)
liquid.registerTag('layout', {
parse: function(token, remainTokens){
var match = lexical.value.exec(token.args);
assert(match, `illegal token ${token.raw}`);
this.layout = match[0]
this.tpls = liquid.parser.parse(remainTokens)
},
render: function (scope, hash) {
var layout = Liquid.evalValue(this.layout, scope)
var register = scope.get('liquid')
this.layout = match[0];
this.tpls = liquid.parser.parse(remainTokens);
},
render: function(scope, hash) {
var layout = Liquid.evalValue(this.layout, scope);
var register = scope.get('liquid');
// render the remaining tokens immediately
return liquid.renderer.renderTemplates(this.tpls, scope)
// now register.blocks contains rendered blocks
.then(() => liquid.getTemplate(layout, register.root))
.then(templates => {
// push the hash
scope.push(hash)
// render the parent
return liquid.renderer.renderTemplates(templates, scope)
})
// pop the hash
.then(partial => {
scope.pop()
return partial
})
}
})
// render the remaining tokens immediately
return liquid.renderer.renderTemplates(this.tpls, scope)
// now register.blocks contains rendered blocks
.then(() => liquid.getTemplate(layout, register.root))
// push the hash
.then(templates => (scope.push(hash), templates))
// render the parent
.then(templates => liquid.renderer.renderTemplates(templates, scope))
// pop the hash
.then(partial => (scope.pop(), partial));
}
});
liquid.registerTag('block', {
parse: function (token, remainTokens) {
var match = /\w+/.exec(token.args)
this.block = match ? match[0] : 'anonymous'
liquid.registerTag('block', {
parse: function(token, remainTokens){
var match = /\w+/.exec(token.args);
this.block = match ? match[0] : 'anonymous';
this.tpls = [];
var stream = liquid.parser.parseStream(remainTokens)
.on('tag:endblock', () => stream.stop())
.on('template', tpl => this.tpls.push(tpl))
.on('end', () => {
throw new Error(`tag ${token.raw} not closed`);
});
stream.start();
},
render: function(scope){
var register = scope.get('liquid');
var html = register.blocks[this.block];
// if not defined yet
if (html === undefined) {
return liquid.renderer.renderTemplates(this.tpls, scope)
.then((partial) => {
register.blocks[this.block] = partial;
return partial;
});
}
// if already defined by desendents
else {
register.blocks[this.block] = html;
return Promise.resolve(html);
}
}
});
};
this.tpls = []
var stream = liquid.parser.parseStream(remainTokens)
.on('tag:endblock', () => stream.stop())
.on('template', tpl => this.tpls.push(tpl))
.on('end', () => {
throw new Error(`tag ${token.raw} not closed`)
})
stream.start()
},
render: function (scope) {
var register = scope.get('liquid')
var html = register.blocks[this.block]
// if not defined yet
if (html === undefined) {
return liquid.renderer.renderTemplates(this.tpls, scope)
.then((partial) => {
register.blocks[this.block] = partial
return partial
})
} else {
// if already defined by desendents
register.blocks[this.block] = html
return Promise.resolve(html)
}
}
})
}
+19 -21
View File
@@ -1,26 +1,24 @@
const Promise = require('any-promise');
const Promise = require('any-promise')
module.exports = function(liquid) {
module.exports = function (liquid) {
liquid.registerTag('raw', {
parse: function (tagToken, remainTokens) {
this.tokens = []
liquid.registerTag('raw', {
parse: function(tagToken, remainTokens) {
this.tokens = [];
var stream = liquid.parser.parseStream(remainTokens);
stream
var stream = liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
if(token.name === 'endraw') stream.stop();
else this.tokens.push(token);
if (token.name === 'endraw') stream.stop()
else this.tokens.push(token)
})
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`);
});
stream.start();
},
render: function(scope, hash) {
var tokens = this.tokens.map(token => token.raw).join('');
return Promise.resolve(tokens);
}
});
};
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
var tokens = this.tokens.map(token => token.raw).join('')
return Promise.resolve(tokens)
}
})
}
+72 -83
View File
@@ -1,95 +1,84 @@
const Liquid = require('..');
const Promise = require('any-promise');
const lexical = Liquid.lexical;
const assert = require('../src/util/assert.js');
const Liquid = require('..')
const mapSeries = require('../src/util/promise.js').mapSeries
const lexical = Liquid.lexical
const assert = require('../src/util/assert.js')
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
`(${lexical.value.source})` +
`(?:\\s+${lexical.hash.source})*$`);
`(${lexical.value.source})` +
`(?:\\s+${lexical.hash.source})*$`)
module.exports = function(liquid) {
liquid.registerTag('tablerow', {
module.exports = function (liquid) {
liquid.registerTag('tablerow', {
parse: function(tagToken, remainTokens) {
var match = re.exec(tagToken.args);
assert(match, `illegal tag: ${tagToken.raw}`);
this.variable = match[1];
this.collection = match[2];
parse: function (tagToken, remainTokens) {
var match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.templates = [];
this.variable = match[1]
this.collection = match[2]
this.templates = []
var p, stream = liquid.parser.parseStream(remainTokens)
.on('start', x => p = this.templates)
.on('tag:endtablerow', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`);
});
var p
var stream = liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates))
.on('tag:endtablerow', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start();
},
stream.start()
},
render: function(scope, hash) {
var collection = Liquid.evalExp(this.collection, scope) || [];
render: function (scope, hash) {
var collection = Liquid.evalExp(this.collection, scope) || []
var html = '<table>';
var offset = hash.offset || 0;
var limit = (hash.limit === undefined) ? collection.length : hash.limit;
var html = '<table>'
var offset = hash.offset || 0
var limit = (hash.limit === undefined) ? collection.length : hash.limit
var cols = hash.cols, row, col;
if (!cols) throw new Error(`illegal cols: ${cols}`);
var cols = hash.cols
var row
var col
if (!cols) throw new Error(`illegal cols: ${cols}`)
// build array of arguments to pass to sequential promises...
collection = collection.slice(offset, offset + limit);
var contexts = [];
collection.some((item, i) => {
var ctx = {};
ctx[this.variable] = item;
// We are just putting together an array of the arguments we will be passing to our sequential promises
contexts.push(ctx);
});
// build array of arguments to pass to sequential promises...
collection = collection.slice(offset, offset + limit)
var contexts = []
collection.some((item, i) => {
var ctx = {}
ctx[this.variable] = item
contexts.push(ctx)
})
// This executes an array of promises sequentially for every argument in the contexts array - http://webcache.googleusercontent.com/search?q=cache:rNbMUn9TPtkJ:joost.vunderink.net/blog/2014/12/15/processing-an-array-of-promises-sequentially-in-node-js/+&cd=5&hl=en&ct=clnk&gl=us
// It's fundamentally equivalent to the following...
// emptyPromise.then(renderTemplates(args0).then(renderTemplates(args1).then(renderTemplates(args2)...
var lastPromise = contexts.reduce((promise, context, currentIndex) => {
return promise.then((partial) => {
row = Math.floor(currentIndex / cols) + 1;
col = (currentIndex % cols) + 1;
if(col === 1) {
if(row !== 1){
html += '</tr>';
}
html += `<tr class="row${row}">`;
}
return mapSeries(contexts,
(context, idx) => {
row = Math.floor(idx / cols) + 1
col = (idx % cols) + 1
if (col === 1) {
if (row !== 1) {
html += '</tr>'
}
html += `<tr class="row${row}">`
}
//ctx[this.variable] = context;
return html += `<td class="col${col}">`;
})
.then((partial) => {
scope.push(context);
return liquid.renderer.renderTemplates(this.templates, scope)
})
.then((partial) => {
scope.pop(context);
html += partial;
return html += '</td>';
});
}, Promise.resolve('')); // start the reduce chain with a resolved Promise. After first run, the "promise" argument
// in our reduce callback will be the returned promise from our "then" above. In this
// case, the promise returned from liquid.renderer.renderTemplates.
return lastPromise
.then(() => {
if(row > 0) {
html += '</tr>';
}
html += '</table>';
return html;
})
.catch((error) => {
throw error;
});
}
});
};
html += `<td class="col${col}">`
scope.push(context)
return liquid.renderer
.renderTemplates(this.templates, scope)
.then((partial) => {
scope.pop(context)
html += partial
html += '</td>'
return html
})
})
.then(() => {
if (row > 0) {
html += '</tr>'
}
html += '</table>'
return html
})
}
})
}
+11
View File
@@ -0,0 +1,11 @@
{
"rules": {
"no-unused-expressions": "off"
},
"env": {
"mocha": true
},
"plugins": [
"mocha"
]
}
+89 -89
View File
@@ -1,94 +1,94 @@
const chai = require("chai");
const expect = chai.expect;
const mock = require('mock-fs');
const request = require('supertest');
const express = require('express');
const Liquid = require('..');
const chai = require('chai')
const expect = chai.expect
const mock = require('mock-fs')
const request = require('supertest')
const express = require('express')
const Liquid = require('..')
describe('engine#express()', function() {
var app, engine;
describe('engine#express()', function () {
var app, engine
beforeEach(function() {
app = express();
engine = Liquid({
root: '/root',
extname: '.html'
});
beforeEach(function () {
app = express()
engine = Liquid({
root: '/root',
extname: '.html'
})
app.set('view engine', 'html');
app.engine('html', engine.express());
app.set('view engine', 'html')
app.engine('html', engine.express())
app.get('/name', (req, res) => res.render('name', {
name: 'harttle'
}));
app.get('/include/:file', (req, res) => res.render('include', {
file: req.params.file
}));
});
after(function() {
mock.restore();
});
it('should render express views', function(done) {
mock({ '/views/name.html': 'My name is {{name}}.' });
app.set('views', ['/views']);
request(app).get('/name')
.expect('My name is harttle.')
.expect(200, done);
});
it('should pass error when file not found', function(done) {
var view = {
root: []
};
var file = '/not-exist.html';
var ctx = {};
engine.express().call(view, file, ctx, function(err) {
try {
expect(err.code).to.equal('ENOENT');
expect(err.message).to.match(/Failed to lookup/);
done();
} catch (e) {
done(e);
}
});
});
it('should respect root option when lookup', function(done) {
mock({
'/root/foo.html': 'foo',
'/views/include.html': '{% include file %}'
});
app.set('views', ['/views']);
request(app).get('/include/foo')
.expect('foo')
.expect(200, done);
});
it('should respect express views (Array) when lookup', function(done) {
mock({
'/views/include.html': '{% include file %}',
'/partials/bar.html': 'bar'
});
app.set('views', ['/views', '/partials']);
request(app).get('/include/bar')
.expect('bar')
.expect(200, done);
});
it('should respect express views (String) when lookup', function(done) {
mock({
'/views/include.html': '{% include file %}',
'/views/bar.html': 'bar'
});
app.set('views', '/views');
request(app).get('/include/bar')
.expect('bar')
.expect(200, done);
});
it('should respect express views (Undefined) when lookup', function(done) {
var files = {};
files[process.cwd() + '/views/include.html'] = '{% include file %}';
files[process.cwd() + '/views/bar.html'] = 'bar';
mock(files);
app.get('/name', (req, res) => res.render('name', {
name: 'harttle'
}))
app.get('/include/:file', (req, res) => res.render('include', {
file: req.params.file
}))
})
after(function () {
mock.restore()
})
it('should render express views', function (done) {
mock({ '/views/name.html': 'My name is {{name}}.' })
app.set('views', ['/views'])
request(app).get('/name')
.expect('My name is harttle.')
.expect(200, done)
})
it('should pass error when file not found', function (done) {
var view = {
root: []
}
var file = '/not-exist.html'
var ctx = {}
engine.express().call(view, file, ctx, function (err) {
try {
expect(err.code).to.equal('ENOENT')
expect(err.message).to.match(/Failed to lookup/)
done()
} catch (e) {
done(e)
}
})
})
it('should respect root option when lookup', function (done) {
mock({
'/root/foo.html': 'foo',
'/views/include.html': '{% include file %}'
})
app.set('views', ['/views'])
request(app).get('/include/foo')
.expect('foo')
.expect(200, done)
})
it('should respect express views (Array) when lookup', function (done) {
mock({
'/views/include.html': '{% include file %}',
'/partials/bar.html': 'bar'
})
app.set('views', ['/views', '/partials'])
request(app).get('/include/bar')
.expect('bar')
.expect(200, done)
})
it('should respect express views (String) when lookup', function (done) {
mock({
'/views/include.html': '{% include file %}',
'/views/bar.html': 'bar'
})
app.set('views', '/views')
request(app).get('/include/bar')
.expect('bar')
.expect(200, done)
})
it('should respect express views (Undefined) when lookup', function (done) {
var files = {}
files[process.cwd() + '/views/include.html'] = '{% include file %}'
files[process.cwd() + '/views/bar.html'] = 'bar'
mock(files)
request(app).get('/include/bar')
.expect('bar')
.expect(200, done);
});
});
request(app).get('/include/bar')
.expect('bar')
.expect(200, done)
})
})
+47 -47
View File
@@ -1,57 +1,57 @@
const chai = require("chai");
const sinon = require("sinon");
const sinonChai = require("sinon-chai");
const expect = chai.expect;
const chai = require('chai')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
const expect = chai.expect
chai.use(sinonChai);
chai.use(sinonChai)
var filter = require('../src/filter.js')();
var Scope = require('../src/scope.js');
var filter = require('../src/filter.js')()
var Scope = require('../src/scope.js')
describe('filter', function() {
var scope;
beforeEach(function() {
filter.clear();
scope = Scope.factory();
});
it('should return default filter when not registered', function() {
var result = filter.construct('foo');
expect(result.name).to.equal('foo');
});
describe('filter', function () {
var scope
beforeEach(function () {
filter.clear()
scope = Scope.factory()
})
it('should return default filter when not registered', function () {
var result = filter.construct('foo')
expect(result.name).to.equal('foo')
})
it('should throw when filter name illegal', function() {
expect(function() {
filter.construct('/');
}).to.throw(/illegal filter/);
});
it('should throw when filter name illegal', function () {
expect(function () {
filter.construct('/')
}).to.throw(/illegal filter/)
})
it('should parse argument syntax', function() {
filter.register('foo', x => x);
var f = filter.construct('foo: a, "b"');
it('should parse argument syntax', function () {
filter.register('foo', x => x)
var f = filter.construct('foo: a, "b"')
expect(f.name).to.equal('foo');
expect(f.args).to.deep.equal(['a', '"b"']);
});
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal(['a', '"b"'])
})
it('should register a simple filter', function() {
filter.register('upcase', x => x.toUpperCase());
expect(filter.construct('upcase').render('foo', scope)).to.equal('FOO');
});
it('should register a simple filter', function () {
filter.register('upcase', x => x.toUpperCase())
expect(filter.construct('upcase').render('foo', scope)).to.equal('FOO')
})
it('should register a argumented filter', function() {
filter.register('add', (a, b) => a + b);
expect(filter.construct('add: 2').render(3, scope)).to.equal(5);
});
it('should register a argumented filter', function () {
filter.register('add', (a, b) => a + b)
expect(filter.construct('add: 2').render(3, scope)).to.equal(5)
})
it('should register a multi-argumented filter', function() {
filter.register('add', (a, b, c) => a + b + c);
expect(filter.construct('add: 2, "c"').render(3, scope)).to.equal("5c");
});
it('should register a multi-argumented filter', function () {
filter.register('add', (a, b, c) => a + b + c)
expect(filter.construct('add: 2, "c"').render(3, scope)).to.equal('5c')
})
it('should call filter with corrct arguments', function() {
var spy = sinon.spy();
filter.register('foo', spy);
filter.construct('foo: 33').render('foo', scope);
expect(spy).to.have.been.calledWith('foo', 33);
});
});
it('should call filter with corrct arguments', function () {
var spy = sinon.spy()
filter.register('foo', spy)
filter.construct('foo: 33').render('foo', scope)
expect(spy).to.have.been.calledWith('foo', 33)
})
})
+298 -261
View File
@@ -1,318 +1,355 @@
const chai = require("chai");
const chaiAsPromised = require("chai-as-promised");
var liquid = require('..')(),
ctx;
chai.use(chaiAsPromised);
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const expect = chai.expect
var liquid = require('..')()
var ctx
chai.use(chaiAsPromised)
function test(src, dst) {
ctx = {
date: new Date(),
foo: 'bar',
arr: [-2, 'a'],
obj: {
foo: 'bar'
},
func: function() {},
posts: [{
category: 'foo'
}, {
category: 'bar'
}]
};
return liquid.parseAndRender(src, ctx).should.eventually.equal(dst);
function test (src, dst) {
ctx = {
date: new Date(),
foo: 'bar',
arr: [-2, 'a'],
obj: {
foo: 'bar'
},
func: function () {},
posts: [{
category: 'foo'
}, {
category: 'bar'
}]
}
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
}
describe('filters', function() {
describe('abs', function() {
it('should return 3 for -3', () => test('{{ -3 | abs }}', '3'));
it('should return 2 for arr[0]', () => test('{{ arr[0] | abs }}', '2'));
});
describe('filters', function () {
describe('abs', function () {
it('should return 3 for -3', () => test('{{ -3 | abs }}', '3'))
it('should return 2 for arr[0]', () => test('{{ arr[0] | abs }}', '2'))
it('should return convert string', () => test('{{ "-3" | abs }}', '3'))
})
describe('append', function() {
it('should return "-3abc" for -3, "abc"',
() => test('{{ -3 | append: "abc" }}', '-3abc'));
it('should return "abar" for "a",foo', () => test('{{ "a" | append: foo }}', 'abar'));
});
describe('append', function () {
it('should return "-3abc" for -3, "abc"',
() => test('{{ -3 | append: "abc" }}', '-3abc'))
it('should return "abar" for "a",foo', () => test('{{ "a" | append: foo }}', 'abar'))
})
it('should support capitalize', () => test('{{ "i am good" | capitalize }}', 'I am good'));
it('should support capitalize', () => test('{{ "i am good" | capitalize }}', 'I am good'))
describe('ceil', function() {
it('should return "2" for 1.2', () => test('{{ 1.2 | ceil }}', '2'));
it('should return "2" for 2.0', () => test('{{ 2.0 | ceil }}', '2'));
it('should return "4" for 3.5', () => test('{{ "3.5" | ceil }}', '4'));
it('should return "184" for 183.357', () => test('{{ 183.357 | ceil }}', '184'));
});
describe('ceil', function () {
it('should return "2" for 1.2', () => test('{{ 1.2 | ceil }}', '2'))
it('should return "2" for 2.0', () => test('{{ 2.0 | ceil }}', '2'))
it('should return "4" for 3.5', () => test('{{ "3.5" | ceil }}', '4'))
it('should return "184" for 183.357', () => test('{{ 183.357 | ceil }}', '184'))
})
describe('date', function() {
it('should support date: %a %b %d %Y', function() {
var str = ctx.date.toDateString();
return test('{{ date | date:"%a %b %d %Y"}}', str);
});
it('should create a new Date when given "now"', function() {
return test('{{ "now" | date: "%Y"}}', (new Date).getFullYear().toString());
});
});
describe('date', function () {
it('should support date: %a %b %d %Y', function () {
var str = ctx.date.toDateString()
return test('{{ date | date:"%a %b %d %Y"}}', str)
})
it('should create a new Date when given "now"', function () {
return test('{{ "now" | date: "%Y"}}', (new Date()).getFullYear().toString())
})
it('should render as empty string when invalid', function () {
return test('{{ "" | date: "%Y"}}', '')
})
})
describe('default', function() {
it('should use default when falsy', () => test('{{false |default: "a"}}', 'a'));
it('should not use default when truthy', () => test('{{true |default: "a"}}', 'true'));
});
describe('default', function () {
it('should use default when falsy', () => test('{{false |default: "a"}}', 'a'))
it('should not use default when truthy', () => test('{{true |default: "a"}}', 'true'))
})
describe('divided_by', function() {
it('should return 2 for 4,2', () => test('{{4 | divided_by: 2}}', '2'));
it('should return 4 for 16,4', () => test('{{16 | divided_by: 4}}', '4'));
it('should return 1 for 5,3', () => test('{{5 | divided_by: 3}}', '1'));
});
describe('divided_by', function () {
it('should return 2 for 4,2', () => test('{{4 | divided_by: 2}}', '2'))
it('should return 4 for 16,4', () => test('{{16 | divided_by: 4}}', '4'))
it('should return 1 for 5,3', () => test('{{5 | divided_by: 3}}', '1'))
it('should convert string to number', () => test('{{"5" | divided_by: "3"}}', '1'))
})
describe('downcase', function() {
it('should return "parker moore" for "Parker Moore"',
() => test('{{ "Parker Moore" | downcase }}', 'parker moore'));
it('should return "apple" for "apple"',
() => test('{{ "apple" | downcase }}', 'apple'));
});
describe('downcase', function () {
it('should return "parker moore" for "Parker Moore"',
() => test('{{ "Parker Moore" | downcase }}', 'parker moore'))
it('should return "apple" for "apple"',
() => test('{{ "apple" | downcase }}', 'apple'))
})
describe('escape', function() {
it('should escape \' and &', function() {
return test('{{ "Have you read \'James & the Giant Peach\'?" | escape }}',
'Have you read &#39;James &amp; the Giant Peach&#39;?');
});
it('should escape normal string', function() {
return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara');
});
it('should escape function', function() {
return test('{{ func | escape }}', 'function () {}');
});
});
describe('escape', function () {
it('should escape \' and &', function () {
return test('{{ "Have you read \'James & the Giant Peach\'?" | escape }}',
'Have you read &#39;James &amp; the Giant Peach&#39;?')
})
it('should escape normal string', function () {
return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara')
})
it('should escape function', function () {
return test('{{ func | escape }}', 'function () {}')
})
})
describe('escape_once', function() {
it('should do escape', () =>
test('{{ "1 < 2 & 3" | escape_once }}', '1 &lt; 2 &amp; 3'));
it('should not escape twice',
() => test('{{ "1 &lt; 2 &amp; 3" | escape_once }}', '1 &lt; 2 &amp; 3'));
});
describe('escape_once', function () {
it('should do escape', () =>
test('{{ "1 < 2 & 3" | escape_once }}', '1 &lt; 2 &amp; 3'))
it('should not escape twice',
() => test('{{ "1 &lt; 2 &amp; 3" | escape_once }}', '1 &lt; 2 &amp; 3'))
})
it('should support split/first', function() {
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}';
return test(src, 'apples');
});
it('should support split/first', function () {
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}'
return test(src, 'apples')
})
describe('floor', function() {
it('should return "1" for 1.2', () => test('{{ 1.2 | floor }}', '1'));
it('should return "2" for 2.0', () => test('{{ 2.0 | floor }}', '2'));
it('should return "183" for 183.357', () => test('{{ 183.357 | floor }}', '183'));
it('should return "3" for 3.5', () => test('{{ "3.5" | floor }}', '3'));
});
describe('floor', function () {
it('should return "1" for 1.2', () => test('{{ 1.2 | floor }}', '1'))
it('should return "2" for 2.0', () => test('{{ 2.0 | floor }}', '2'))
it('should return "183" for 183.357', () => test('{{ 183.357 | floor }}', '183'))
it('should return "3" for 3.5', () => test('{{ "3.5" | floor }}', '3'))
})
it('should support join', function() {
var src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
'{{ beatles | join: " and " }}';
return test(src, 'John and Paul and George and Ringo');
});
it('should support join', function () {
var src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
'{{ beatles | join: " and " }}'
return test(src, 'John and Paul and George and Ringo')
})
it('should support split/last', function() {
var src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
'{{ my_array|last }}';
return test(src, 'tiger');
});
it('should support split/last', function () {
var src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
'{{ my_array|last }}'
return test(src, 'tiger')
})
it('should support lstrip', function() {
var src = '{{ " So much room for activities! " | lstrip }}';
return test(src, 'So much room for activities! ');
});
it('should support lstrip', function () {
var src = '{{ " So much room for activities! " | lstrip }}'
return test(src, 'So much room for activities! ')
})
it('should support map', function() {
return test('{{posts | map: "category"}}', '["foo","bar"]');
});
it('should support map', function () {
return test('{{posts | map: "category"}}', '["foo","bar"]')
})
describe('minus', function() {
it('should return "2" for 4,2', () => test('{{ 4 | minus: 2 }}', '2'));
it('should return "12" for 16,4', () => test('{{ 16 | minus: 4 }}', '12'));
it('should return "171.357" for 183.357,12',
() => test('{{ 183.357 | minus: 12 }}', '171.357'));
});
describe('minus', function () {
it('should return "2" for 4,2', () => test('{{ 4 | minus: 2 }}', '2'))
it('should return "12" for 16,4', () => test('{{ 16 | minus: 4 }}', '12'))
it('should return "171.357" for 183.357,12',
() => test('{{ 183.357 | minus: 12 }}', '171.357'))
it('should convert first arg as number', () => test('{{ "4" | minus: 1 }}', '3'))
it('should convert both args as number', () => test('{{ "4" | minus: "1" }}', '3'))
})
describe('modulo', function() {
it('should return "1" for 3,2', () => test('{{ 3 | modulo: 2 }}', '1'));
it('should return "3" for 24,7', () => test('{{ 24 | modulo: 7 }}', '3'));
it('should return "3.357" for 183.357,12',
() => test('{{ 183.357 | modulo: 12 }}', '3.357'));
});
describe('modulo', function () {
it('should return "1" for 3,2', () => test('{{ 3 | modulo: 2 }}', '1'))
it('should return "3" for 24,7', () => test('{{ 24 | modulo: 7 }}', '3'))
it('should return "3.357" for 183.357,12',
() => test('{{ 183.357 | modulo: 12 }}', '3.357'))
it('should convert string', () => test('{{ "24" | modulo: "7" }}', '3'))
})
it('should support string_with_newlines', function() {
var src = '{% capture string_with_newlines %}\n' +
it('should support string_with_newlines', function () {
var src = '{% capture string_with_newlines %}\n' +
'Hello\n' +
'there\n' +
'{% endcapture %}' +
'{{ string_with_newlines | newline_to_br }}';
var dst = '<br />' +
'{{ string_with_newlines | newline_to_br }}'
var dst = '<br />' +
'Hello<br />' +
'there<br />';
return test(src, dst);
});
'there<br />'
return test(src, dst)
})
describe('plus', function() {
it('should return "6" for 4,2', () => test('{{ 4 | plus: 2 }}', '6'));
it('should return "20" for 16,4', () => test('{{ 16 | plus: 4 }}', '20'));
it('should return "195.357" for 183.357,12',
() => test('{{ 183.357 | plus: 12 }}', '195.357'));
});
describe('plus', function () {
it('should return "6" for 4,2', () => test('{{ 4 | plus: 2 }}', '6'))
it('should return "20" for 16,4', () => test('{{ 16 | plus: 4 }}', '20'))
it('should return "195.357" for 183.357,12',
() => test('{{ 183.357 | plus: 12 }}', '195.357'))
it('should convert first arg as number', () => test('{{ "4" | plus: 2 }}', '6'))
it('should convert both args as number', () => test('{{ "4" | plus: "2" }}', '6'))
})
it('should support prepend', function() {
return test('{% assign url = "liquidmarkup.com" %}' +
it('should support prepend', function () {
return test('{% assign url = "liquidmarkup.com" %}' +
'{{ "/index.html" | prepend: url }}',
'liquidmarkup.com/index.html');
});
'liquidmarkup.com/index.html')
})
it('should support remove', function() {
return test('{{ "I strained to see the train through the rain" | remove: "rain" }}',
'I sted to see the t through the ');
});
it('should support remove', function () {
return test('{{ "I strained to see the train through the rain" | remove: "rain" }}',
'I sted to see the t through the ')
})
it('should support remove_first', function() {
return test('{{ "I strained to see the train through the rain" | remove_first: "rain" }}',
'I sted to see the train through the rain');
});
it('should support remove_first', function () {
return test('{{ "I strained to see the train through the rain" | remove_first: "rain" }}',
'I sted to see the train through the rain')
})
it('should support replace', function() {
return test('{{ "Take my protein pills and put my helmet on" | replace: "my", "your" }}',
'Take your protein pills and put your helmet on');
});
it('should support replace', function () {
return test('{{ "Take my protein pills and put my helmet on" | replace: "my", "your" }}',
'Take your protein pills and put your helmet on')
})
it('should support replace_first', function() {
return test('{% assign my_string = "Take my protein pills and put my helmet on" %}\n' +
it('should support replace_first', function () {
return test('{% assign my_string = "Take my protein pills and put my helmet on" %}\n' +
'{{ my_string | replace_first: "my", "your" }}',
'\nTake your protein pills and put my helmet on');
});
'\nTake your protein pills and put my helmet on')
})
it('should support reverse', function() {
return test('{{ "Ground control to Major Tom." | split: "" | reverse | join: "" }}',
'.moT rojaM ot lortnoc dnuorG');
});
it('should support reverse', function () {
return test('{{ "Ground control to Major Tom." | split: "" | reverse | join: "" }}',
'.moT rojaM ot lortnoc dnuorG')
})
describe('round', function() {
it('should return "1" for 1.2', () => test('{{1.2|round}}', '1'));
it('should return "3" for 2.7', () => test('{{2.7|round}}', '3'));
it('should return "183.36" for 183.357,2',
() => test('{{183.357|round: 2}}', '183.36'));
});
describe('round', function () {
it('should return "1" for 1.2', () => test('{{1.2|round}}', '1'))
it('should return "3" for 2.7', () => test('{{2.7|round}}', '3'))
it('should return "183.36" for 183.357,2',
() => test('{{183.357|round: 2}}', '183.36'))
it('should convert string to number', () => test('{{"2.7"|round}}', '3'))
})
it('should support rstrip', function() {
return test('{{ " So much room for activities! " | rstrip }}',
' So much room for activities!');
});
it('should support rstrip', function () {
return test('{{ " So much room for activities! " | rstrip }}',
' So much room for activities!')
})
describe('size', function() {
it('should return string length',
() => test('{{ "Ground control to Major Tom." | size }}', '28'));
it('should return array size', function() {
return test('{% assign my_array = "apples, oranges, peaches, plums"' +
describe('size', function () {
it('should return string length',
() => test('{{ "Ground control to Major Tom." | size }}', '28'))
it('should return array size', function () {
return test('{% assign my_array = "apples, oranges, peaches, plums"' +
' | split: ", " %}{{ my_array | size }}',
'4');
});
});
'4')
})
it('should also be used with dot notation - string',
() => test('{% assign my_string = "Ground control to Major Tom." %}{{ my_string.size }}', '28'))
it('should also be used with dot notation - array',
() => test('{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}{{ my_array.size }}', '4'))
})
describe('slice', function() {
it('should slice first char by 0', () => test('{{ "Liquid" | slice: 0 }}', 'L'));
it('should slice third char by 2', () => test('{{ "Liquid" | slice: 2 }}', 'q'));
it('should slice substr by 2,5', () => test('{{ "Liquid" | slice: 2, 5 }}', 'quid'));
it('should slice substr by -3,2', () => test('{{ "Liquid" | slice: -3, 2 }}', 'ui'));
});
describe('slice', function () {
it('should slice first char by 0', () => test('{{ "Liquid" | slice: 0 }}', 'L'))
it('should slice third char by 2', () => test('{{ "Liquid" | slice: 2 }}', 'q'))
it('should slice substr by 2,5', () => test('{{ "Liquid" | slice: 2, 5 }}', 'quid'))
it('should slice substr by -3,2', () => test('{{ "Liquid" | slice: -3, 2 }}', 'ui'))
})
it('should support sort', function() {
return test('{% assign my_array = "zebra, octopus, giraffe, Sally Snake"' +
it('should support sort', function () {
return test('{% assign my_array = "zebra, octopus, giraffe, Sally Snake"' +
' | split: ", " %}' +
'{{ my_array | sort | join: ", " }}',
'Sally Snake, giraffe, octopus, zebra');
});
'Sally Snake, giraffe, octopus, zebra')
})
it('should support split', function() {
return test('{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
it('should support split', function () {
return test('{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
'{% for member in beatles %}' +
'{{ member }} ' +
'{% endfor %}',
'John Paul George Ringo ');
});
'John Paul George Ringo ')
})
it('should support strip', function() {
return test('{{ " So much room for activities! " | strip }}',
'So much room for activities!');
});
it('should support strip', function () {
return test('{{ " So much room for activities! " | strip }}',
'So much room for activities!')
})
describe('strip_html', function() {
it('should strip all tags', function() {
return test('{{ "Have <em>you</em> read <strong>Ulysses</strong>?" | strip_html }}',
'Have you read Ulysses?');
});
it('should strip until empty', function() {
return test('{{"<br/><br />< p ></p></ p >" | strip_html }}', '');
});
});
describe('strip_html', function () {
it('should strip all tags', function () {
return test('{{ "Have <em>you</em> read <strong>Ulysses</strong>?" | strip_html }}',
'Have you read Ulysses?')
})
it('should strip until empty', function () {
return test('{{"<br/><br />< p ></p></ p >" | strip_html }}', '')
})
})
it('should support strip_newlines', function() {
return test('{% capture string_with_newlines %}\n' +
it('should support strip_newlines', function () {
return test('{% capture string_with_newlines %}\n' +
'Hello\nthere\n{% endcapture %}' +
'{{ string_with_newlines | strip_newlines }}',
'Hellothere');
});
'Hellothere')
})
describe('times', function() {
it('should return "6" for 3,2', () => test('{{ 3 | times: 2 }}', '6'));
it('should return "168" for 24,7', () => test('{{ 24 | times: 7 }}', '168'));
it('should return "2200.284" for 183.357,12',
() => test('{{ 183.357 | times: 12 }}', '2200.284'));
});
describe('times', function () {
it('should return "6" for 3,2', () => test('{{ 3 | times: 2 }}', '6'))
it('should return "168" for 24,7', () => test('{{ 24 | times: 7 }}', '168'))
it('should return "2200.284" for 183.357,12',
() => test('{{ 183.357 | times: 12 }}', '2200.284'))
it('should convert string to number', () => test('{{ "24" | times: "7" }}', '168'))
})
describe('truncate', function() {
it('should truncate when string too long', function() {
return test('{{ "Ground control to Major Tom." | truncate: 20 }}',
'Ground control to...');
});
it('should not truncate when string not long enough', function() {
return test('{{ "Ground control to Major Tom." | truncate: 80 }}',
'Ground control to Major Tom.');
});
it('should truncate with custom ellipsis', function() {
return test('{{ "Ground control to Major Tom." | truncate: 25,", and so on" }}',
'Ground control, and so on');
});
it('should truncate with empty custom ellipsis', function() {
return test('{{ "Ground control to Major Tom." | truncate: 20, "" }}',
'Ground control to Ma');
});
});
describe('truncate', function () {
it('should truncate when string too long', function () {
return test('{{ "Ground control to Major Tom." | truncate: 20 }}',
'Ground control to...')
})
it('should not truncate when string not long enough', function () {
return test('{{ "Ground control to Major Tom." | truncate: 80 }}',
'Ground control to Major Tom.')
})
it('should truncate with custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncate: 25,", and so on" }}',
'Ground control, and so on')
})
it('should truncate with empty custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncate: 20, "" }}',
'Ground control to Ma')
})
it('should not truncate when short enough', function () {
return test('{{ "12345" | truncate: 5 }}', '12345')
})
it('should default to 16', function () {
return test('{{ "1234567890abcdefghi" | truncate }}', '1234567890abc...')
})
})
describe('truncatewords', function() {
it('should truncate when too many words', function() {
return test('{{ "Ground control to Major Tom." | truncatewords: 3 }}',
'Ground control to...');
});
it('should not truncate when not enough words', function() {
return test('{{ "Ground control to Major Tom." | truncatewords: 8 }}',
'Ground control to Major Tom.');
});
it('should truncate with custom ellipsis', function() {
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "--" }}',
'Ground control to--');
});
it('should truncate with empty custom ellipsis', function() {
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "" }}',
'Ground control to');
});
});
describe('truncatewords', function () {
it('should truncate when too many words', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 3 }}',
'Ground control to...')
})
it('should not truncate when not enough words', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 8 }}',
'Ground control to Major Tom.')
})
it('should truncate with custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "--" }}',
'Ground control to--')
})
it('should truncate with empty custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "" }}',
'Ground control to')
})
})
it('should support uniq', function() {
return test('{% assign my_array = "ants, bugs, bees, bugs, ants" | split: ", " %}' +
'{{ my_array | uniq | join: ", " }}',
'ants, bugs, bees');
});
describe('uniq', function () {
it('should uniq string list', function () {
return test(
'{% assign my_array = "ants, bugs, bees, bugs, ants" | split: ", " %}' +
'{{ my_array | uniq | join: ", " }}',
'ants, bugs, bees'
)
})
it('should uniq falsy value', function () {
return test('{{"" | uniq | join: ","}}', '')
})
})
it('should support upcase', () => test('{{ "Parker Moore" | upcase }}', 'PARKER MOORE'));
it('should support upcase', () => test('{{ "Parker Moore" | upcase }}', 'PARKER MOORE'))
describe('url_encode', function() {
it('should encode @',
() => test('{{ "[email protected]" | url_encode }}', 'john%40liquid.com'));
it('should encode <space>',
() => test('{{ "Tetsuro Takara" | url_encode }}', 'Tetsuro%20Takara'));
});
});
describe('url_encode', function () {
it('should encode @',
() => test('{{ "[email protected]" | url_encode }}', 'john%40liquid.com'))
it('should encode <space>',
() => test('{{ "Tetsuro Takara" | url_encode }}', 'Tetsuro%20Takara'))
})
describe('obj_test', function () {
liquid.registerFilter('obj_test', function () {
return Array.prototype.slice.call(arguments).join(',')
})
it('should support object', () => test('{{ "a" | obj_test: k1: "v1", k2: "v2" }}', 'a,k1,v1,k2,v2'))
})
})
+119 -110
View File
@@ -1,122 +1,131 @@
const chai = require("chai");
const expect = chai.expect;
const chai = require('chai')
const expect = chai.expect
var lexical = require('../src/lexical.js');
var lexical = require('../src/lexical.js')
describe('lexical', function() {
it('should test filter syntax', function() {
lexical.filterLine.test('abs').should.equal(true);
lexical.filterLine.test('plus:1').should.equal(true);
lexical.filterLine.test('replace: "a", b').should.equal(true);
lexical.filterLine.test('foo: a, "b"').should.equal(true);
lexical.filterLine.test('abs | another').should.equal(false);
lexical.filterLine.test('join: "," | another').should.equal(false);
});
it('should test boolean literal', function() {
lexical.isLiteral('true').should.equal(true);
lexical.isLiteral('TrUE').should.equal(true);
lexical.isLiteral('false').should.equal(true);
});
describe('lexical', function () {
it('should test filter syntax', function () {
expect(lexical.filterLine.test('abs')).to.equal(true)
expect(lexical.filterLine.test('plus:1')).to.equal(true)
expect(lexical.filterLine.test('replace: "a", b')).to.equal(true)
expect(lexical.filterLine.test('foo: a, "b"')).to.equal(true)
expect(lexical.filterLine.test('abs | another')).to.equal(false)
expect(lexical.filterLine.test('join: "," | another')).to.equal(false)
expect(lexical.filterLine.test('obj_test: k1: "v1", k2: "v2"')).to.equal(true)
})
it('should test number literal', function() {
lexical.isLiteral('2.3').should.equal(true);
lexical.isLiteral('.3').should.equal(true);
lexical.isLiteral('-3.').should.equal(true);
lexical.isLiteral('23').should.equal(true);
});
it('should test boolean literal', function () {
expect(lexical.isLiteral('true')).to.equal(true)
expect(lexical.isLiteral('TrUE')).to.equal(true)
expect(lexical.isLiteral('false')).to.equal(true)
})
it("should test range literal", function() {
lexical.isRange("(12..32)").should.equal(true);
lexical.isRange("(12..foo)").should.equal(true);
lexical.isRange("(foo.bar..foo)").should.equal(true);
});
it('should test number literal', function () {
expect(lexical.isLiteral('2.3')).to.equal(true)
expect(lexical.isLiteral('.3')).to.equal(true)
expect(lexical.isLiteral('-3.')).to.equal(true)
expect(lexical.isLiteral('23')).to.equal(true)
})
it('should test string literal', function() {
lexical.isLiteral('""').should.equal(true);
lexical.isLiteral('"a\'b"').should.equal(true);
lexical.isLiteral("''").should.equal(true);
lexical.isLiteral("'a bcd'").should.equal(true);
});
it('should test range literal', function () {
expect(lexical.isRange('(12..32)')).to.equal(true)
expect(lexical.isRange('(12..foo)')).to.equal(true)
expect(lexical.isRange('(foo.bar..foo)')).to.equal(true)
})
describe('.isVariable()', function() {
it('should return true for foo', function() {
lexical.isVariable("foo").should.equal(true);
});
it('should return true for.bar.foo', function() {
lexical.isVariable("foo.bar.foo").should.equal(true);
});
it('should return true for foo[0].b', function() {
lexical.isVariable("foo[0].b").should.equal(true);
});
it('should return true for 0a', function() {
lexical.isVariable("0a").should.equal(true);
});
it('should return true for foo[a.b]', function() {
lexical.isVariable("foo[a.b]").should.equal(true);
});
it('should return true for foo[a.b]', function() {
lexical.isVariable("foo['a[0]']").should.equal(true);
});
it('should return true for "var-1"', function() {
lexical.isVariable("var-1").should.equal(true);
});
it('should return true for "-var"', function() {
lexical.isVariable("-var").should.equal(true);
});
it('should return true for "var-"', function() {
lexical.isVariable("var-").should.equal(true);
});
it('should return true for "3-4"', function() {
lexical.isVariable("3-4").should.equal(true);
});
});
it('should test string literal', function () {
expect(lexical.isLiteral('""')).to.equal(true)
expect(lexical.isLiteral('"a\'b"')).to.equal(true)
expect(lexical.isLiteral("''")).to.equal(true)
expect(lexical.isLiteral("'a bcd'")).to.equal(true)
})
it('should test none literal', function() {
lexical.isLiteral('2a').should.equal(false);
lexical.isLiteral('"x').should.equal(false);
lexical.isLiteral('a2').should.equal(false);
});
describe('.isVariable()', function () {
it('should return true for foo', function () {
expect(lexical.isVariable('foo')).to.equal(true)
})
it('should return true for.bar.foo', function () {
expect(lexical.isVariable('foo.bar.foo')).to.equal(true)
})
it('should return true for foo[0].b', function () {
expect(lexical.isVariable('foo[0].b')).to.equal(true)
})
it('should return true for 0a', function () {
expect(lexical.isVariable('0a')).to.equal(true)
})
it('should return true for foo[a.b]', function () {
expect(lexical.isVariable('foo[a.b]')).to.equal(true)
})
it('should return true for foo[a.b]', function () {
expect(lexical.isVariable("foo['a[0]']")).to.equal(true)
})
it('should return true for "var-1"', function () {
expect(lexical.isVariable('var-1')).to.equal(true)
})
it('should return true for "-var"', function () {
expect(lexical.isVariable('-var')).to.equal(true)
})
it('should return true for "var-"', function () {
expect(lexical.isVariable('var-')).to.equal(true)
})
it('should return true for "3-4"', function () {
expect(lexical.isVariable('3-4')).to.equal(true)
})
})
it('should test none variable', function() {
lexical.isVariable("a.").should.equal(false);
lexical.isVariable(".b").should.equal(false);
lexical.isVariable(".").should.equal(false);
lexical.isVariable("[0][12].bar[0]").should.equal(false);
});
it('should test none literal', function () {
expect(lexical.isLiteral('2a')).to.equal(false)
expect(lexical.isLiteral('"x')).to.equal(false)
expect(lexical.isLiteral('a2')).to.equal(false)
})
it('should parse boolean literal', function() {
lexical.parseLiteral('true').should.equal(true);
lexical.parseLiteral('TrUE').should.equal(true);
lexical.parseLiteral('false').should.equal(false);
});
it('should test none variable', function () {
expect(lexical.isVariable('a.')).to.equal(false)
expect(lexical.isVariable('.b')).to.equal(false)
expect(lexical.isVariable('.')).to.equal(false)
expect(lexical.isVariable('[0][12].bar[0]')).to.equal(false)
})
it('should parse number literal', function() {
lexical.parseLiteral('2.3').should.equal(2.3);
lexical.parseLiteral('.32').should.equal(0.32);
lexical.parseLiteral('-23.').should.equal(-23);
lexical.parseLiteral('23').should.equal(23);
});
describe('.parseLiteral()', function () {
it('should parse boolean literal', function () {
expect(lexical.parseLiteral('true')).to.equal(true)
expect(lexical.parseLiteral('TrUE')).to.equal(true)
expect(lexical.parseLiteral('false')).to.equal(false)
})
it('should parse string literal', function() {
lexical.parseLiteral('"ab\'c"').should.equal("ab\'c");
});
it('should parse number literal', function () {
expect(lexical.parseLiteral('2.3')).to.equal(2.3)
expect(lexical.parseLiteral('.32')).to.equal(0.32)
expect(lexical.parseLiteral('-23.')).to.equal(-23)
expect(lexical.parseLiteral('23')).to.equal(23)
})
describe('.matchValue()', function(){
it('should match -5-5', function() {
var match = lexical.matchValue('-5-5');
expect(match && match[0]).to.equal('-5-5');
});
it('should match 4-3', function() {
var match = lexical.matchValue('4-3');
expect(match && match[0]).to.equal('4-3');
});
it('should match 4-3', function() {
var match = lexical.matchValue('4-3');
expect(match && match[0]).to.equal('4-3');
});
it('should match var-1', function() {
var match = lexical.matchValue('var-1');
expect(match && match[0]).to.equal('var-1');
});
});
});
it('should parse string literal', function () {
expect(lexical.parseLiteral('"ab\'c"')).to.equal("ab'c")
})
it('should throw if non-literal', function () {
var fn = () => lexical.parseLiteral('a')
expect(fn).to.throw("cannot parse 'a' as literal")
})
})
describe('.matchValue()', function () {
it('should match -5-5', function () {
var match = lexical.matchValue('-5-5')
expect(match && match[0]).to.equal('-5-5')
})
it('should match 4-3', function () {
var match = lexical.matchValue('4-3')
expect(match && match[0]).to.equal('4-3')
})
it('should match 4-3', function () {
var match = lexical.matchValue('4-3')
expect(match && match[0]).to.equal('4-3')
})
it('should match var-1', function () {
var match = lexical.matchValue('var-1')
expect(match && match[0]).to.equal('var-1')
})
})
})
+229 -174
View File
@@ -1,177 +1,232 @@
const chai = require("chai");
const expect = chai.expect;
const Liquid = require('..');
const mock = require('mock-fs');
chai.use(require("chai-as-promised"));
const chai = require('chai')
const expect = chai.expect
const Liquid = require('..')
const mock = require('mock-fs')
chai.use(require('chai-as-promised'))
describe('liquid', function() {
var engine, strictEngine, ctx;
beforeEach(function() {
ctx = {
name: 'harttle',
arr: [-2, 'a'],
obj: {
foo: 'bar'
}
};
engine = Liquid({
root: '/root/',
extname: '.html'
});
strictEngine = Liquid({
root: '/root',
extname: '.html',
strict_filters: true
});
mock({
'/root/files/foo.html': 'foo',
'/root/files/name.html': 'My name is {{name}}.',
'/un-readable.html': mock.file({
mode: '0000'
})
});
});
afterEach(function() {
mock.restore();
});
describe('{{output}}', function() {
it('should output object', function() {
return engine.parseAndRender('{{obj}}', ctx).should.eventually.equal('{"foo":"bar"}');
});
it('should output array', function() {
return engine.parseAndRender('{{arr}}', ctx).should.eventually.equal('[-2,"a"]');
});
it('should output undefined to empty', function() {
return engine.parseAndRender('foo{{zzz}}bar', ctx).should.eventually.equal('foobar');
});
it('should render as null when filter undefined', function() {
return engine.parseAndRender('{{"foo" | filter1}}', ctx).should.eventually.equal('foo');
});
it('should throw upon undefined filter when strict_filters set', function() {
return expect(strictEngine.parseAndRender('{{arr | filter1}}', ctx)).to
.be.rejectedWith(/undefined filter: filter1/);
});
});
it('should parse html', function() {
(function() {
engine.parse('{{obj}}');
}).should.not.throw();
(function() {
engine.parse('<html><head>{{obj}}</head></html>');
}).should.not.throw();
});
it('should render template multiple times', function() {
var template = engine.parse('{{obj}}');
describe('liquid', function () {
var engine, strictEngine, ctx
beforeEach(function () {
ctx = {
name: 'harttle',
arr: [-2, 'a'],
obj: {
foo: 'bar'
}
}
engine = Liquid({
root: '/root/',
extname: '.html'
})
strictEngine = Liquid({
root: '/root',
extname: '.html',
strict_filters: true
})
mock({
'/root/files/foo.html': 'foo',
'/root/files/name.html': 'My name is {{name}}.',
'/un-readable.html': mock.file({
mode: '0000'
})
})
})
afterEach(function () {
mock.restore()
})
describe('Liquid', function () {
it('should ignore invalid root option', function () {
var liquid = Liquid({ root: /regex/ })
expect(liquid.options.root).to.deep.equal([])
})
})
describe('{{output}}', function () {
it('should output object', function () {
return expect(engine.parseAndRender('{{obj}}', ctx)).to.eventually.equal('{"foo":"bar"}')
})
it('should output array', function () {
return expect(engine.parseAndRender('{{arr}}', ctx)).to.eventually.equal('[-2,"a"]')
})
it('should output undefined to empty', function () {
return expect(engine.parseAndRender('foo{{zzz}}bar', ctx)).to.eventually.equal('foobar')
})
it('should render as null when filter undefined', function () {
return expect(engine.parseAndRender('{{"foo" | filter1}}', ctx)).to.eventually.equal('foo')
})
it('should throw upon undefined filter when strict_filters set', function () {
return expect(strictEngine.parseAndRender('{{arr | filter1}}', ctx)).to
.be.rejectedWith(/undefined filter: filter1/)
})
})
it('should parse html', function () {
expect(function () {
engine.parse('{{obj}}')
}).to.not.throw()
expect(function () {
engine.parse('<html><head>{{obj}}</head></html>')
}).to.not.throw()
})
it('should render template multiple times', function () {
var template = engine.parse('{{obj}}')
return engine.render(template, ctx)
.then((result) => {
expect(result).to.equal('{"foo":"bar"}')
return engine.render(template, ctx)
.then((result) => {
expect(result).to.equal('{"foo":"bar"}');
return engine.render(template, ctx);
})
.then((result) => {
return expect(result).to.equal('{"foo":"bar"}');
});
});
it('should render filters', function() {
var template = engine.parse('<p>{{arr | join: "_"}}</p>');
return engine.render(template, ctx).should.eventually.equal('<p>-2_a</p>');
});
it('should render accessive filters', function() {
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}';
return expect(engine.parseAndRender(src)).to.eventually.equal('apples');
});
describe('#renderFile()', function() {
it('should render file', function() {
return expect(engine.renderFile('/root/files/foo.html', ctx))
.to.eventually.equal('foo');
});
it('should accept relative path', function() {
return expect(engine.renderFile('files/foo.html'))
.to.eventually.equal('foo');
});
it('should resolve array as root', function(){
engine = Liquid({
root: ['/boo', '/root/'],
extname: '.html'
});
return expect(engine.renderFile('files/foo.html'))
.to.eventually.equal('foo');
});
it('should default root to cwd', function(){
var files = {};
files[process.cwd() + '/foo.html'] = 'FOO';
mock(files);
})
.then((result) => {
return expect(result).to.equal('{"foo":"bar"}')
})
})
it('should render filters', function () {
var template = engine.parse('<p>{{arr | join: "_"}}</p>')
return expect(engine.render(template, ctx)).to.eventually.equal('<p>-2_a</p>')
})
it('should render accessive filters', function () {
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}'
return expect(engine.parseAndRender(src)).to.eventually.equal('apples')
})
describe('#renderFile()', function () {
it('should render file', function () {
return expect(engine.renderFile('/root/files/foo.html', ctx))
.to.eventually.equal('foo')
})
it('should accept relative path', function () {
return expect(engine.renderFile('files/foo.html'))
.to.eventually.equal('foo')
})
it('should resolve array as root', function () {
engine = Liquid({
root: ['/boo', '/root/'],
extname: '.html'
})
return expect(engine.renderFile('files/foo.html'))
.to.eventually.equal('foo')
})
it('should default root to cwd', function () {
var files = {}
files[process.cwd() + '/foo.html'] = 'FOO'
mock(files)
engine = Liquid({
extname: '.html'
});
return expect(engine.renderFile('foo.html'))
.to.eventually.equal('FOO');
});
it('should render file with context', function() {
return engine.renderFile('/root/files/name.html', ctx).should.eventually.equal('My name is harttle.');
});
it('should use default extname', function() {
return engine.renderFile('files/name', ctx).should.eventually.equal('My name is harttle.');
});
it('should throw with lookup list when file not exist', function() {
engine = Liquid({
root: ['/boo', '/root/'],
extname: '.html'
});
return expect(engine.renderFile('/not/exist.html')).to
.be.rejectedWith(/failed to lookup \/not\/exist.html in: \/boo,\/root\//i);
});
it('should throw when file not readable', function() {
return expect(engine.renderFile('/un-readable.html')).to
.be.rejectedWith(/EACCES/);
});
});
describe('strict', function() {
it('should not throw when strict_variables false (default)', function() {
return expect(engine.parseAndRender('before{{notdefined}}after', ctx)).to
.eventually.equal('beforeafter');
});
it('should throw when strict_variables true', function() {
var tpl = engine.parse('before{{notdefined}}after');
var opts = {
strict_variables: true
};
return expect(engine.render(tpl, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/);
});
it('should pass strict_variables to render by parseAndRender', function() {
var html = 'before{{notdefined}}after';
var opts = {
strict_variables: true
};
return expect(engine.parseAndRender(html, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/);
});
});
describe('cache', function() {
it('should be disabled by default', function() {
return engine.renderFile('files/foo')
.then(x => expect(x).to.equal('foo'))
.then(() => mock({
'/root/files/foo.html': 'bar'
}))
.then(() => engine.renderFile('files/foo'))
.then(x => expect(x).to.equal('bar'));
});
it('should respect cache=true option', function() {
engine = Liquid({
root: '/root/',
extname: '.html',
cache: true
});
return engine.renderFile('files/foo')
.then(x => expect(x).to.equal('foo'))
.then(() => mock({
'/root/files/foo.html': 'bar'
}))
.then(() => engine.renderFile('files/foo'))
.then(x => expect(x).to.equal('foo'));
});
});
});
engine = Liquid({
extname: '.html'
})
return expect(engine.renderFile('foo.html'))
.to.eventually.equal('FOO')
})
it('should render file with context', function () {
return expect(engine.renderFile('/root/files/name.html', ctx)).to.eventually.equal('My name is harttle.')
})
it('should use default extname', function () {
return expect(engine.renderFile('files/name', ctx)).to.eventually.equal('My name is harttle.')
})
it('should throw with lookup list when file not exist', function () {
engine = Liquid({
root: ['/boo', '/root/'],
extname: '.html'
})
return expect(engine.renderFile('/not/exist.html')).to
.be.rejectedWith(/failed to lookup \/not\/exist.html in: \/boo,\/root\//i)
})
it('should throw when file not readable', function () {
return expect(engine.renderFile('/un-readable.html')).to
.be.rejectedWith(/EACCES/)
})
})
describe('strict', function () {
it('should not throw when strict_variables false (default)', function () {
return expect(engine.parseAndRender('before{{notdefined}}after', ctx)).to
.eventually.equal('beforeafter')
})
it('should throw when strict_variables true', function () {
var tpl = engine.parse('before{{notdefined}}after')
var opts = {
strict_variables: true
}
return expect(engine.render(tpl, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/)
})
it('should pass strict_variables to render by parseAndRender', function () {
var html = 'before{{notdefined}}after'
var opts = {
strict_variables: true
}
return expect(engine.parseAndRender(html, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/)
})
})
describe('cache', function () {
it('should be disabled by default', function () {
return engine.renderFile('files/foo')
.then(x => expect(x).to.equal('foo'))
.then(() => mock({
'/root/files/foo.html': 'bar'
}))
.then(() => engine.renderFile('files/foo'))
.then(x => expect(x).to.equal('bar'))
})
it('should respect cache=true option', function () {
engine = Liquid({
root: '/root/',
extname: '.html',
cache: true
})
return engine.renderFile('files/foo')
.then(x => expect(x).to.equal('foo'))
.then(() => mock({
'/root/files/foo.html': 'bar'
}))
.then(() => engine.renderFile('files/foo'))
.then(x => expect(x).to.equal('foo'))
})
})
describe('trim_left, trim_right', function () {
it('should trim_left for tags when trim_left=true', function () {
engine = Liquid({
trim_left: true
})
return expect(engine.parseAndRender(' \n \t{%if true%}foo{%endif%} '))
.to.eventually.equal(' \nfoo ')
})
it('should trim_right for tags when trim_right=true', function () {
engine = Liquid({
trim_right: true
})
return expect(engine.parseAndRender('\t{%if true%}foo{%endif%} \n'))
.to.eventually.equal('\tfoo')
})
it('should trim all blanks before and after when greedy=true', function () {
engine = Liquid({
greedy: true
})
return expect(engine.parseAndRender('\t{%-if true%}foo{%endif-%} \n \n'))
.to.eventually.equal('foo')
})
it('should support trim using markup', function () {
engine = Liquid()
var src = [
'{%- assign username = "John G. Chalmers-Smith" -%}',
'{%- if username and username.length > 10 -%}',
' Wow, {{ username }}, you have a long name!',
'{%- else -%}',
' Hello there!',
'{%- endif -%}\n'
].join('\n')
var dst = ' Wow, John G. Chalmers-Smith, you have a long name!\n'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
})
it('should not trim when not specified', function () {
engine = Liquid()
var src = [
'{% assign username = "John G. Chalmers-Smith" %}',
'{% if username and username.length > 10 %}',
' Wow, {{ username }}, you have a long name!',
'{% else %}',
' Hello there!',
'{% endif %}\n'
].join('\n')
var dst = '\n\n Wow, John G. Chalmers-Smith, you have a long name!\n\n'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
})
})
})
+38 -40
View File
@@ -1,49 +1,47 @@
const chai = require("chai");
const sinon = require("sinon");
const sinonChai = require("sinon-chai");
const should = chai.should();
const expect = chai.expect;
const chai = require('chai')
const expect = chai.expect
chai.use(sinonChai);
chai.use(require('sinon-chai'))
var filter = require('../src/filter.js')();
var tag = require('../src/tag.js')();
var Template = require('../src/parser.js');
var filter = require('../src/filter.js')()
var tag = require('../src/tag.js')()
var Template = require('../src/parser.js')
describe('template', function() {
var scope, template, add = (l, r) => l + r;
describe('template', function () {
var template
var add = (l, r) => l + r
beforeEach(function() {
filter.clear();
filter.register('add', add);
beforeEach(function () {
filter.clear()
filter.register('add', add)
tag.clear();
template = Template(tag, filter);
});
tag.clear()
template = Template(tag, filter)
})
it('should throw when output string illegal', function() {
expect(function() {
template.parseOutput('/');
}).to.throw(/illegal output string/);
});
it('should throw when output string illegal', function () {
expect(function () {
template.parseOutput('/')
}).to.throw(/illegal output string/)
})
it('should parse output string', function() {
var tpl = template.parseOutput('foo');
expect(tpl.type).to.equal('output');
expect(tpl.initial).to.equal('foo');
expect(tpl.filters).to.deep.equal([]);
});
it('should parse output string', function () {
var tpl = template.parseOutput('foo')
expect(tpl.type).to.equal('output')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters).to.deep.equal([])
})
it('should parse output string with a simple filter', function() {
var tpl = template.parseOutput('foo | add: 3, "foo"');
expect(tpl.initial).to.equal('foo');
expect(tpl.filters.length).to.equal(1);
expect(tpl.filters[0].filter).to.equal(add);
});
it('should parse output string with a simple filter', function () {
var tpl = template.parseOutput('foo | add: 3, "foo"')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters.length).to.equal(1)
expect(tpl.filters[0].filter).to.equal(add)
})
it('should parse output string with filters', function() {
var tpl = template.parseOutput('foo | add: "|" | add');
expect(tpl.initial).to.equal('foo');
expect(tpl.filters.length).to.equal(2);
});
});
it('should parse output string with filters', function () {
var tpl = template.parseOutput('foo | add: "|" | add')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters.length).to.equal(2)
})
})
+58 -59
View File
@@ -1,67 +1,66 @@
const chai = require("chai");
const chaiAsPromised = require("chai-as-promised");
const should = chai.should();
const expect = chai.expect;
const sinonChai = require("sinon-chai");
const sinon = require("sinon");
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const expect = chai.expect
const sinonChai = require('sinon-chai')
const sinon = require('sinon')
chai.use(sinonChai);
chai.use(chaiAsPromised);
chai.use(sinonChai)
chai.use(chaiAsPromised)
var tag = require('../src/tag.js')();
var Scope = require('../src/scope.js');
var filter = require('../src/filter')();
var Render = require('../src/render.js');
var Template = require('../src/parser.js')(tag, filter);
var tag = require('../src/tag.js')()
var Scope = require('../src/scope.js')
var filter = require('../src/filter')()
var Render = require('../src/render.js')
var Template = require('../src/parser.js')(tag, filter)
describe('render', function() {
var scope, render;
describe('render', function () {
var scope, render
beforeEach(function() {
scope = Scope.factory({
foo: {
bar: ['a', 2]
}
});
filter.clear();
tag.clear();
render = Render();
});
beforeEach(function () {
scope = Scope.factory({
foo: {
bar: ['a', 2]
}
})
filter.clear()
tag.clear()
render = Render()
})
describe('.renderTemplates()', function(){
it('should throw when scope undefined', function() {
expect(function(){
render.renderTemplates([]);
}).to.throw(/scope undefined/);
});
describe('.renderTemplates()', function () {
it('should throw when scope undefined', function () {
expect(function () {
render.renderTemplates([])
}).to.throw(/scope undefined/)
})
it('should render html', function() {
return render.renderTemplates([{type: 'html', value: '<p>'}], scope).should.eventually.equal('<p>');
});
});
it('should render html', function () {
return expect(render.renderTemplates([{type: 'html', value: '<p>'}], scope)).to.eventually.equal('<p>')
})
})
it('should eval filter with correct arguments', function() {
var date = sinon.stub().returns('y');
var time = sinon.spy();
filter.register('date', date);
filter.register('time', time);
var tpl = Template.parseOutput('foo.bar[0] | date: "b" | time:2');
render.evalOutput(tpl, scope);
expect(date).to.have.been.calledWith('a', 'b');
expect(time).to.have.been.calledWith('y', 2);
});
it('should eval filter with correct arguments', function () {
var date = sinon.stub().returns('y')
var time = sinon.spy()
filter.register('date', date)
filter.register('time', time)
var tpl = Template.parseOutput('foo.bar[0] | date: "b" | time:2')
render.evalOutput(tpl, scope)
expect(date).to.have.been.calledWith('a', 'b')
expect(time).to.have.been.calledWith('y', 2)
})
describe('.evalOutput()', function(){
it('should throw when scope undefined', function() {
expect(function(){
render.evalOutput();
}).to.throw(/scope undefined/);
});
it('should eval output', function() {
filter.register('date', (l, r) => l + r);
filter.register('time', (l, r) => l + 3 * r);
var tpl = Template.parseOutput('foo.bar[0] | date: "b" | time:2');
expect(render.evalOutput(tpl, scope)).to.equal('ab6');
});
});
});
describe('.evalOutput()', function () {
it('should throw when scope undefined', function () {
expect(function () {
render.evalOutput()
}).to.throw(/scope undefined/)
})
it('should eval output', function () {
filter.register('date', (l, r) => l + r)
filter.register('time', (l, r) => l + 3 * r)
var tpl = Template.parseOutput('foo.bar[0] | date: "b" | time:2')
expect(render.evalOutput(tpl, scope)).to.equal('ab6')
})
})
})
+206 -172
View File
@@ -1,189 +1,223 @@
const chai = require("chai");
const expect = chai.expect;
const chai = require('chai')
const expect = chai.expect
var Scope = require('../src/scope.js');
var Scope = require('../src/scope.js')
describe('scope', function() {
var scope, ctx;
beforeEach(function() {
ctx = {
foo: 'zoo',
bar: {
zoo: 'coo',
"Mr.Smith": 'John',
arr: ['a', 'b']
}
};
scope = Scope.factory(ctx);
});
describe('scope', function () {
var scope, ctx
beforeEach(function () {
ctx = {
foo: 'zoo',
bar: {
zoo: 'coo',
'Mr.Smith': 'John',
arr: ['a', 'b']
}
}
scope = Scope.factory(ctx)
})
describe('#propertyAccessSeq()', function() {
it('should handle dot syntax', function() {
expect(scope.propertyAccessSeq('foo.bar'))
.to.deep.equal(['foo', 'bar']);
});
it('should handle [<String>] syntax', function() {
expect(scope.propertyAccessSeq('foo["bar"]'))
.to.deep.equal(['foo', 'bar']);
});
it('should handle [<Identifier>] syntax', function() {
expect(scope.propertyAccessSeq('foo[foo]'))
.to.deep.equal(['foo', 'zoo']);
});
it('should handle nested access', function() {
expect(scope.propertyAccessSeq('foo[bar.zoo]'))
.to.deep.equal(['foo', 'coo']);
expect(scope.propertyAccessSeq('foo[bar["zoo"]]'))
.to.deep.equal(['foo', 'coo']);
});
});
describe('#propertyAccessSeq()', function () {
it('should handle dot syntax', function () {
expect(scope.propertyAccessSeq('foo.bar'))
.to.deep.equal(['foo', 'bar'])
})
it('should handle [<String>] syntax', function () {
expect(scope.propertyAccessSeq('foo["bar"]'))
.to.deep.equal(['foo', 'bar'])
})
it('should handle [<Identifier>] syntax', function () {
expect(scope.propertyAccessSeq('foo[foo]'))
.to.deep.equal(['foo', 'zoo'])
})
it('should handle nested access 1', function () {
expect(scope.propertyAccessSeq('foo[bar.zoo]'))
.to.deep.equal(['foo', 'coo'])
})
it('should handle nested access 2', function () {
expect(scope.propertyAccessSeq('foo[bar["zoo"]]'))
.to.deep.equal(['foo', 'coo'])
})
it('should handle nested access 3', function () {
expect(scope.propertyAccessSeq('bar["foo"].zoo'))
.to.deep.equal(['bar', 'foo', 'zoo'])
})
it('should handle nested access 4', function () {
expect(scope.propertyAccessSeq('foo[0].bar'))
.to.deep.equal(['foo', '0', 'bar'])
})
})
describe('#get()', function() {
it('should get direct property', function() {
expect(scope.get('foo')).equal('zoo');
});
describe('#get()', function () {
it('should get direct property', function () {
expect(scope.get('foo')).equal('zoo')
})
it('should get undefined property', function() {
function fn() {
scope.get('notdefined');
}
expect(fn).to.not.throw();
expect(scope.get('notdefined')).to.equal(undefined);
expect(scope.get('')).to.equal(undefined);
expect(scope.get(false)).to.equal(undefined);
});
it('should get undefined property', function () {
function fn () {
scope.get('notdefined')
}
expect(fn).to.not.throw()
expect(scope.get('notdefined')).to.equal(undefined)
expect(scope.get('')).to.equal(undefined)
expect(scope.get(false)).to.equal(undefined)
})
it('should throw when [] unbalanced', function() {
expect(function() {
scope.get('foo[bar');
}).to.throw(/unbalanced \[\]/);
});
it('should throw when [] unbalanced', function () {
expect(function () {
scope.get('foo[bar')
}).to.throw(/unbalanced \[\]/)
})
it('should throw when "" unbalanced', function() {
expect(function() {
scope.get('foo["bar]');
}).to.throw(/unbalanced "/);
});
it('should throw when "" unbalanced', function () {
expect(function () {
scope.get('foo["bar]')
}).to.throw(/unbalanced "/)
})
it("should throw when '' unbalanced", function() {
expect(function() {
scope.get("foo['bar]");
}).to.throw(/unbalanced '/);
});
it("should throw when '' unbalanced", function () {
expect(function () {
scope.get("foo['bar]")
}).to.throw(/unbalanced '/)
})
it('should access child property via dot syntax', function() {
expect(scope.get('bar.zoo')).to.equal('coo');
expect(scope.get('bar.arr')).to.deep.equal(['a', 'b']);
});
it('should access child property via dot syntax', function () {
expect(scope.get('bar.zoo')).to.equal('coo')
expect(scope.get('bar.arr')).to.deep.equal(['a', 'b'])
})
it('should access child property via [<String>] syntax', function() {
expect(scope.get('bar["zoo"]')).to.equal('coo');
});
it('should access child property via [<String>] syntax', function () {
expect(scope.get('bar["zoo"]')).to.equal('coo')
})
it('should access child property via [<Number>] syntax', function() {
expect(scope.get('bar.arr[0]')).to.equal('a');
});
it('should access child property via [<Number>] syntax', function () {
expect(scope.get('bar.arr[0]')).to.equal('a')
})
it('should access child property via [<Identifier>] syntax', function() {
expect(scope.get('bar[foo]')).to.equal('coo');
});
it('should access child property via [<Identifier>] syntax', function () {
expect(scope.get('bar[foo]')).to.equal('coo')
})
it('should support nested case', function() {
scope.set('posts', {
"first": {
"name": "A Nice Day"
}
});
scope.set('category', {
"diary": ["first"]
});
expect(scope.get('posts[category.diary[0]].name'), 'A Nice Day');
});
});
it('should return undefined when not exist', function () {
expect(scope.get('foo.foo.foo')).to.be.undefined
})
})
describe('strict_variables', function() {
var scope;
beforeEach(function(){
scope = Scope.factory(ctx, {
strict_variables: true
});
});
it('should throw undefined in strict mode', function() {
function fn() {
scope.get('notdefined');
}
expect(fn).to.throw(/undefined variable: notdefined/);
});
it('should find variable in parent scope', function() {
scope.set('foo', 'foo');
scope.push({
'bar': 'bar'
});
expect(scope.get('foo')).to.equal('foo');
});
});
describe('#set', function () {
it('should set nested value', function () {
scope.set('posts', {
'first': {
'name': 'A Nice Day'
}
})
scope.set('category', {
'diary': ['first']
})
expect(scope.get('posts[category.diary[0]].name'), 'A Nice Day')
})
describe('.getAll()', function() {
it('should get all properties when arguments empty', function() {
expect(scope.getAll()).deep.equal(ctx);
});
});
it('should create in parent scope if needed', function () {
scope.push({})
scope.set('bar.coo', 'COO')
expect(scope.get('bar.coo')).to.equal('COO')
})
it("should set parents' corresponding value", function () {
scope.push({})
scope.set('foo', 'bar')
scope.pop()
expect(scope.get('foo')).to.equal('bar')
})
})
describe('strict_variables', function () {
var scope
beforeEach(function () {
scope = Scope.factory(ctx, {
strict_variables: true
})
})
it('should throw when variable not defined', function () {
function fn () {
scope.get('notdefined')
}
expect(fn).to.throw(/undefined variable: notdefined/)
})
it('should throw when deep variable not exist', function () {
scope.set('foo', 'bar')
function fn () {
scope.get('foo.bar.not.defined')
}
expect(fn).to.throw(/undefined variable: not/)
})
it('should find variable in parent scope', function () {
scope.set('foo', 'foo')
scope.push({
'bar': 'bar'
})
expect(scope.get('foo')).to.equal('foo')
})
})
describe('.push()', function() {
it('should throw when trying to push non-object', function() {
expect(function() {
scope.push(false);
}).to.throw();
});
it('should push scope', function() {
scope.set('bar', 'bar');
scope.push({
foo: 'foo'
});
expect(scope.get('foo')).to.equal('foo');
expect(scope.get('bar')).to.equal('bar');
});
it('should hide deep properties by push', function(){
scope.set('bar', {bar: 'bar'});
scope.push({bar: {foo: 'foo'}});
expect(scope.get('bar.foo')).to.equal('foo');
expect(scope.get('bar.bar')).to.equal(undefined);
});
});
describe('.pop()', function() {
it('should pop scope', function() {
scope.push({
foo: 'foo'
});
scope.pop();
expect(scope.get('foo')).to.equal('zoo');
});
});
describe('.getAll()', function () {
it('should get all properties when arguments empty', function () {
expect(scope.getAll()).deep.equal(ctx)
})
})
describe('.unshift()', function() {
it('should throw when trying to unshift non-object', function() {
expect(function() {
scope.unshift(false);
}).to.throw();
});
it('should unshift scope', function() {
scope.unshift({
foo: 'blue',
foo1: 'foo1'
});
expect(scope.get('foo')).to.equal('zoo');
expect(scope.get('foo1')).to.equal('foo1');
});
});
describe('.shift()', function() {
it('should shift scope', function() {
scope.unshift({
foo: 'blue',
foo1: 'foo1'
});
scope.shift();
expect(scope.get('foo')).to.equal('zoo');
expect(scope.get('foo1')).to.equal(undefined);
});
});
});
describe('.push()', function () {
it('should throw when trying to push non-object', function () {
expect(function () {
scope.push(false)
}).to.throw()
})
it('should push scope', function () {
scope.set('bar', 'bar')
scope.push({
foo: 'foo'
})
expect(scope.get('foo')).to.equal('foo')
expect(scope.get('bar')).to.equal('bar')
})
it('should hide deep properties by push', function () {
scope.set('bar', {bar: 'bar'})
scope.push({bar: {foo: 'foo'}})
expect(scope.get('bar.foo')).to.equal('foo')
expect(scope.get('bar.bar')).to.equal(undefined)
})
})
describe('.pop()', function () {
it('should pop scope', function () {
scope.push({
foo: 'foo'
})
scope.pop()
expect(scope.get('foo')).to.equal('zoo')
})
})
describe('.unshift()', function () {
it('should throw when trying to unshift non-object', function () {
expect(function () {
scope.unshift(false)
}).to.throw()
})
it('should unshift scope', function () {
scope.unshift({
foo: 'blue',
foo1: 'foo1'
})
expect(scope.get('foo')).to.equal('zoo')
expect(scope.get('foo1')).to.equal('foo1')
})
})
describe('.shift()', function () {
it('should shift scope', function () {
scope.unshift({
foo: 'blue',
foo1: 'foo1'
})
scope.shift()
expect(scope.get('foo')).to.equal('zoo')
expect(scope.get('foo1')).to.equal(undefined)
})
})
})
+76 -54
View File
@@ -1,65 +1,87 @@
const chai = require("chai");
const expect = chai.expect;
var syntax = require('../src/syntax.js');
var Scope = require('../src/scope.js');
const chai = require('chai')
const expect = chai.expect
var syntax = require('../src/syntax.js')
var Scope = require('../src/scope.js')
var evalExp = syntax.evalExp;
var evalValue = syntax.evalValue;
var evalExp = syntax.evalExp
var evalValue = syntax.evalValue
var isTruthy = syntax.isTruthy
describe('expression', function() {
var scope;
describe('expression', function () {
var scope
beforeEach(function() {
scope = Scope.factory({
one: 1,
two: 2,
x: 'XXX'
});
});
beforeEach(function () {
scope = Scope.factory({
one: 1,
two: 2,
x: 'XXX',
y: undefined,
z: null
})
})
it('should eval literals', function() {
expect(evalValue('2.3')).to.equal(2.3);
expect(evalValue('"foo"')).to.equal("foo");
});
describe('.evalValue()', function () {
it('should eval literals', function () {
expect(evalValue('2.3')).to.equal(2.3)
expect(evalValue('"foo"')).to.equal('foo')
})
it('should throw on illegal expression', function() {
expect(function() {
evalExp('1 contains "x"', scope);
}).to.throw();
});
it('should eval variables', function () {
expect(evalValue('23', scope)).to.equal(23)
expect(evalValue('one', scope)).to.equal(1)
expect(evalValue('x', scope)).to.equal('XXX')
})
it('should eval variables', function() {
expect(evalValue('23', scope)).to.equal(23);
expect(evalValue('one', scope)).to.equal(1);
expect(evalValue('x', scope)).to.equal('XXX');
});
it('should throw if not valid', function () {
var fn = () => evalValue('===')
expect(fn).to.throw("cannot eval '===' as value")
})
})
describe('.evalExp()', function() {
describe('.isTruthy()', function () {
// Spec: https://shopify.github.io/liquid/basics/truthy-and-falsy/
expect(isTruthy(true)).to.be.true
expect(isTruthy(false)).to.be.false
expect(isTruthy(null)).to.be.false
expect(isTruthy('foo')).to.be.true
expect(isTruthy('')).to.be.true
expect(isTruthy(0)).to.be.true
expect(isTruthy(1)).to.be.true
expect(isTruthy(1.1)).to.be.true
expect(isTruthy([1])).to.be.true
expect(isTruthy([])).to.be.true
})
it('should throw when scope undefined', function() {
expect(function() {
evalExp('');
}).to.throw(/scope undefined/);
});
describe('.evalExp()', function () {
it('should throw when scope undefined', function () {
expect(function () {
evalExp('')
}).to.throw(/scope undefined/)
})
it('should eval simple expression', function() {
expect(evalExp('1<2', scope)).to.equal(true);
expect(evalExp('2<=2', scope)).to.equal(true);
expect(evalExp('one<=two', scope)).to.equal(true);
expect(evalExp('x contains "x"', scope)).to.equal(false);
expect(evalExp('x contains "X"', scope)).to.equal(true);
expect(evalExp('"<=" == "<="', scope)).to.equal(true);
});
it('should eval simple expression', function () {
expect(evalExp('1<2', scope)).to.equal(true)
expect(evalExp('2<=2', scope)).to.equal(true)
expect(evalExp('one<=two', scope)).to.equal(true)
expect(evalExp('x contains "x"', scope)).to.equal(false)
expect(evalExp('x contains "X"', scope)).to.equal(true)
expect(evalExp('1 contains "x"', scope)).to.equal(false)
expect(evalExp('y contains "x"', scope)).to.equal(false)
expect(evalExp('z contains "x"', scope)).to.equal(false)
expect(evalExp('(1..5) contains 3', scope)).to.equal(true)
expect(evalExp('(1..5) contains 6', scope)).to.equal(false)
expect(evalExp('"<=" == "<="', scope)).to.equal(true)
})
it('should eval complex expression', function() {
expect(evalExp('1<2 and x contains "x"', scope)).to.equal(false);
expect(evalExp('1<2 or x contains "x"', scope)).to.equal(true);
expect(evalExp('false or true', scope)).to.equal(true);
});
it('should eval complex expression', function () {
expect(evalExp('1<2 and x contains "x"', scope)).to.equal(false)
expect(evalExp('1<2 or x contains "x"', scope)).to.equal(true)
expect(evalExp('false or true', scope)).to.equal(true)
})
it("should eval range expression", function() {
expect(evalExp('(2..4)', scope)).to.deep.equal([2, 3, 4]);
expect(evalExp('(two..4)', scope)).to.deep.equal([2, 3, 4]);
});
});
});
it('should eval range expression', function () {
expect(evalExp('(2..4)', scope)).to.deep.equal([2, 3, 4])
expect(evalExp('(two..4)', scope)).to.deep.equal([2, 3, 4])
})
})
})
+92 -67
View File
@@ -1,73 +1,98 @@
const chai = require("chai");
const sinon = require("sinon");
const expect = chai.expect;
chai.use(require("sinon-chai"));
const chai = require('chai')
const sinon = require('sinon')
const expect = chai.expect
chai.use(require('sinon-chai'))
var tag = require('../src/tag.js')();
var Scope = require('../src/scope.js');
var tag = require('../src/tag.js')()
var Scope = require('../src/scope.js')
describe('tag', function() {
var scope;
before(function() {
scope = Scope.factory({
foo: 'bar',
arr: [2, 1]
});
tag.clear();
});
describe('tag', function () {
var scope
before(function () {
scope = Scope.factory({
foo: 'bar',
arr: [2, 1],
bar: {
coo: 'uoo'
}
})
tag.clear()
})
it('should throw when not registered', function() {
expect(function() {
tag.construct({
type: 'tag',
value: 'foo',
name: 'foo'
}, []);
}).to.throw(/tag foo not found/);
});
it('should throw when not registered', function () {
expect(function () {
tag.construct({
type: 'tag',
value: 'foo',
name: 'foo'
}, [])
}).to.throw(/tag foo not found/)
})
it('should register simple tag', function() {
expect(
function() {
tag.register('foo', {
render: x => 'bar'
});
}).not.throw();
});
it('should register simple tag', function () {
expect(function () {
tag.register('foo', {
render: x => 'bar'
})
}).not.throw()
})
it('should call tag.render', function() {
var spy = sinon.spy(),
tokens = [];
tag.register('foo', {
render: spy
});
return tag
.construct({
type: 'tag',
value: 'foo',
name: 'foo'
}, [])
.render(scope, {})
.then(() => expect(spy).to.have.been.called);
});
it('should call tag.render', function () {
var spy = sinon.spy()
tag.register('foo', {
render: spy
})
return tag
.construct({
type: 'tag',
value: 'foo',
name: 'foo'
}, [])
.render(scope, {})
.then(() => expect(spy).to.have.been.called)
})
it('should call tag.render with resolved hash', function() {
var spy = sinon.spy(),
tokens = [];
tag.register('foo', {
render: spy
});
var token = {
type: 'tag',
value: 'foo aa:foo bb: arr[0] cc: 2.3',
name: 'foo',
args: 'aa:foo bb: arr[0] cc: 2.3'
};
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch(scope, {
aa: 'bar',
bb: 2,
cc: 2.3
}));
});
});
describe('hash', function () {
var spy, token
beforeEach(function () {
spy = sinon.spy()
tag.register('foo', {
render: spy
})
token = {
type: 'tag',
value: 'foo aa:foo bb: arr[0] cc: 2.3\ndd:bar.coo',
name: 'foo',
args: 'aa:foo bb: arr[0] cc: 2.3\ndd:bar.coo'
}
})
it('should call tag.render with scope', function () {
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch(scope))
})
it('should resolve identifier hash', function () {
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch({}, {
aa: 'bar'
}))
})
it('should accept space between key/value', function () {
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch({}, {
bb: 2
}))
})
it('should resolve number value hash', function () {
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch(scope, {
cc: 2.3
}))
})
it('should resolve property access hash', function () {
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch(scope, {
dd: 'uoo'
}))
})
})
})
+51 -51
View File
@@ -1,53 +1,53 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/assign', function() {
var liquid = Liquid();
it('should throw when variable expression illegal', function() {
var src = '{% assign / %}';
var ctx = {};
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/);
});
describe('tags/assign', function () {
var liquid = Liquid()
it('should throw when variable expression illegal', function () {
var src = '{% assign / %}'
var ctx = {}
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/)
})
it('should assign as string', function() {
var src = '{% assign foo="bar" %}{{foo}}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('bar');
});
it('should assign as array', function() {
var src = '{% assign foo=(1..3) %}{{foo}}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('[1,2,3]');
});
it('should assign as filter result', function() {
var src = '{% assign foo="a b" | capitalize | split: " " | first %}{{foo}}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('A');
});
it('should assign var-1', function() {
var src = '{% assign var-1 = 5 %}{{ var-1 }}';
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
});
it('should assign var-', function() {
var src = '{% assign var- = 5 %}{{ var- }}';
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
});
it('should assign -var', function() {
var src = '{% assign -var = 5 %}{{ -var }}';
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
});
it('should assign -5-5', function() {
var src = '{% assign -5-5 = 5 %}{{ -5-5 }}';
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
});
it('should assign 4-3', function() {
var src = '{% assign 4-3 = 5 %}{{ 4-3 }}';
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
});
it('should not assign -6', function() {
var src = '{% assign -6 = 5 %}{{ -6 }}';
return expect(liquid.parseAndRender(src)).to.eventually.equal('-6');
});
});
it('should assign as string', function () {
var src = '{% assign foo="bar" %}{{foo}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('bar')
})
it('should assign as array', function () {
var src = '{% assign foo=(1..3) %}{{foo}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('[1,2,3]')
})
it('should assign as filter result', function () {
var src = '{% assign foo="a b" | capitalize | split: " " | first %}{{foo}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('A')
})
it('should assign var-1', function () {
var src = '{% assign var-1 = 5 %}{{ var-1 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should assign var-', function () {
var src = '{% assign var- = 5 %}{{ var- }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should assign -var', function () {
var src = '{% assign -var = 5 %}{{ -var }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should assign -5-5', function () {
var src = '{% assign -5-5 = 5 %}{{ -5-5 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should assign 4-3', function () {
var src = '{% assign 4-3 = 5 %}{{ 4-3 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should not assign -6', function () {
var src = '{% assign -6 = 5 %}{{ -6 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('-6')
})
})
+22 -22
View File
@@ -1,26 +1,26 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/capture', function() {
var liquid = Liquid();
describe('tags/capture', function () {
var liquid = Liquid()
it('should support capture', function() {
var src = '{% capture f %}{{"a" | capitalize}}{%endcapture%}{{f}}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('A');
});
it('should support capture', function () {
var src = '{% capture f %}{{"a" | capitalize}}{%endcapture%}{{f}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('A')
})
it('should throw on invalid identifier', function() {
var src = '{% capture = %}{%endcapture%}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/= not valid identifier/);
});
it('should throw on invalid identifier', function () {
var src = '{% capture = %}{%endcapture%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/= not valid identifier/)
})
it('should throw when capture not closed', function() {
var src = '{%capture c%}{{c}}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/);
});
});
it('should throw when capture not closed', function () {
var src = '{%capture c%}{{c}}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/)
})
})
+46 -39
View File
@@ -1,45 +1,52 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/case', function() {
var liquid = Liquid();
describe('tags/case', function () {
var liquid = Liquid()
it('should support case 1', function() {
var src = '{% case "foo"%}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% case "foo"%} not closed/);
});
it('should support case 2', function() {
var src = '{% case "foo"%}' +
it('should reject if not closed', function () {
var src = '{% case "foo"%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% case "foo"%} not closed/)
})
it('should hit the specified case', function () {
var src = '{% case "foo"%}' +
'{% when "foo" %}foo{% when "bar"%}bar' +
'{%endcase%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('foo');
});
it('should support case 3', function() {
var src = '{% case empty %}' +
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('foo')
})
it('should resolve empty string if not hit', function () {
var src = '{% case empty %}' +
'{% when "foo" %}foo{% when ""%}bar' +
'{%endcase%}';
var ctx = {
empty: ''
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('bar');
});
it('should support case 4', function() {
var src = '{% case false %}' +
'{%endcase%}'
var ctx = {
empty: ''
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('bar')
})
it('should accept empty string as branch name', function () {
var src = '{% case false %}' +
'{% when "foo" %}foo{% when ""%}bar' +
'{%endcase%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('');
});
it('should support case 5', function() {
var src = '{% case "a" %}' +
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
it('should support boolean case', function () {
var src = '{% case false %}' +
'{% when "foo" %}foo{% when false%}bar' +
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('bar')
})
it('should support else branch', function () {
var src = '{% case "a" %}' +
'{% when "b" %}b{% when "c"%}c{%else %}d' +
'{%endcase%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('d');
});
});
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('d')
})
})
+22 -22
View File
@@ -1,23 +1,23 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/comment', function() {
var liquid = Liquid();
it('should support comment 1', function() {
var src = '{% comment %}{% raw%}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% comment %} not closed/);
});
it('should support comment 2', function() {
var src = 'My name is {% comment %}super{% endcomment %} Shopify.';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('My name is Shopify.');
});
it('should support comment 3', function() {
var src = '{% comment %}\n{{ foo}} \n{% endcomment %}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('');
});
});
describe('tags/comment', function () {
var liquid = Liquid()
it('should support comment 1', function () {
var src = '{% comment %}{% raw%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% comment %} not closed/)
})
it('should support comment 2', function () {
var src = 'My name is {% comment %}super{% endcomment %} Shopify.'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('My name is Shopify.')
})
it('should support comment 3', function () {
var src = '{% comment %}\n{{ foo}} \n{% endcomment %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
})
+33 -33
View File
@@ -1,39 +1,39 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/cycle', function() {
var liquid = Liquid();
describe('tags/cycle', function () {
var liquid = Liquid()
it('should support cycle', function() {
var src = "{% cycle '1', '2', '3' %}";
return expect(liquid.parseAndRender(src + src + src + src))
.to.eventually.equal('1231');
});
it('should support cycle', function () {
var src = "{% cycle '1', '2', '3' %}"
return expect(liquid.parseAndRender(src + src + src + src))
.to.eventually.equal('1231')
})
it('should throw when cycle candidates empty', function() {
return expect(liquid.parseAndRender('{%cycle%}'))
.to.be.rejectedWith(/empty candidates/);
});
it('should throw when cycle candidates empty', function () {
return expect(liquid.parseAndRender('{%cycle%}'))
.to.be.rejectedWith(/empty candidates/)
})
it('should support cycle in for block', function() {
var src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}';
var ctx = {
one: 1
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1e1e1');
});
it('should support cycle in for block', function () {
var src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}'
var ctx = {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1e1e1')
})
it('should support cycle group', function() {
var src = "{% cycle one: '1', '2', '3'%}" +
it('should support cycle group', function () {
var src = "{% cycle one: '1', '2', '3'%}" +
"{% cycle 1: '1', '2', '3'%}" +
"{% cycle 2: '1', '2', '3'%}";
var ctx = {
one: 1
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('121');
});
});
"{% cycle 2: '1', '2', '3'%}"
var ctx = {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('121')
})
})
+33 -33
View File
@@ -1,38 +1,38 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/decrement', function() {
var liquid = Liquid();
describe('tags/decrement', function () {
var liquid = Liquid()
it('should throw when variable expression illegal', function() {
var src = '{% decrement / %}{{one}}';
var ctx = {};
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/);
});
it('should throw when variable expression illegal', function () {
var src = '{% decrement / %}{{one}}'
var ctx = {}
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/)
})
it('should support decrement', function() {
var src = '{% decrement one %}{{one}}';
var ctx = {
one: 1
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('0');
});
it('should support decrement', function () {
var src = '{% decrement one %}{{one}}'
var ctx = {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('0')
})
it('should decrement undefined', function() {
var src = '{% decrement empty %}{{empty}}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1');
});
it('should decrement undefined', function () {
var src = '{% decrement empty %}{{empty}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1')
})
it('should support decrement multiple times', function() {
var src = '{% decrement foo %}{%decrement foo%}{{foo}}';
var ctx = {
foo: 1
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('-1');
});
});
it('should support decrement multiple times', function () {
var src = '{% decrement foo %}{%decrement foo%}{{foo}}'
var ctx = {
foo: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('-1')
})
})
+151 -69
View File
@@ -1,82 +1,164 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/for', function() {
var liquid, ctx;
before(function() {
liquid = Liquid();
ctx = {
one: 1,
alpha: ['a', 'b', 'c'],
};
});
it('should support for', function() {
var src = '{%for c in alpha%}{{c}}{%endfor%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('abc');
});
describe('tags/for', function () {
var liquid, ctx
before(function () {
liquid = Liquid()
liquid.registerTag('throwingTag', {
render: function () { throw new Error('intended render error') }
})
ctx = {
one: 1,
// eslint-disable-next-line
strObj: new String(''),
emptyObj: {},
nullProtoObj: Object.create(null),
obj: {foo: 'bar', coo: 'haa'},
alpha: ['a', 'b', 'c'],
emptyArray: []
}
})
it('should support array', function () {
var src = '{%for c in alpha%}{{c}}{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('abc')
})
it('should throw when for not closed', function() {
var src = '{%for c in alpha%}{{c}}';
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag .* not closed/);
});
it('should support object', function () {
var src = '{%for item in obj%}{{item[0]}},{{item[1]}}-{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('foo,bar-coo,haa-')
})
it('should support for else', function() {
var src = '{%for c in ""%}a{%else%}b{%endfor%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b');
});
describe('scope', function () {
it('should read super scope', function () {
var src = '{%for a in (1..2)%}{{num}}{%endfor%}'
return expect(liquid.parseAndRender(src, {num: 1}))
.to.eventually.equal('11')
})
it('should write super scope', function () {
var src = '{%for a in (1..2)%}{{num}}{%assign num = 2%}{%endfor%}'
return expect(liquid.parseAndRender(src, {num: 1}))
.to.eventually.equal('12')
})
})
it('should support for with forloop', function() {
var src = '{%for c in alpha%}' +
describe('illegal', function () {
it('should reject when for not closed', function () {
var src = '{%for c in alpha%}{{c}}'
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag .* not closed/)
})
it('should reject when inner templates rejected', function () {
var src = '{%for c in alpha%}{%throwingTag%}{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/intended render error/)
})
})
describe('else', function () {
it('should goto else for empty array', function () {
var src = '{%for c in emptyArray%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should treat non-empty string as one single element', function () {
var src = '{%for c in "abc"%}x{{c}}{%else%}y{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('xabc')
})
it('should goto else for empty string', function () {
var src = '{%for c in ""%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should goto else for empty string object', function () {
// it should be false although `new String` is none-conform
var src = '{%for c in strObj%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should goto else for empty object', function () {
var src = '{%for c in emptyObj%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should goto else for null-prototyped object', function () {
var src = '{%for c in nullProtoObj%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
})
it('should support for with forloop', function () {
var src = '{%for c in alpha%}' +
'{{forloop.first}}.{{forloop.index}}.{{forloop.index0}}.' +
'{{forloop.last}}.{{forloop.length}}.' +
'{{forloop.rindex}}.{{forloop.rindex0}}' +
'{{c}}\n' +
'{%endfor%}';
var dst = 'true.1.0.false.3.3.2a\n' +
'{%endfor%}'
var dst = 'true.1.0.false.3.3.2a\n' +
'false.2.1.false.3.2.1b\n' +
'false.3.2.true.3.1.0c\n';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal(dst);
});
'false.3.2.true.3.1.0c\n'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal(dst)
})
it('should support for with continue', function() {
var src = '{% for i in (1..5) %}' +
it('should support for with continue', function () {
var src = '{% for i in (1..5) %}' +
'{{i}}{% continue %}after' +
'{% endfor %}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12345');
});
it('should support for with break', function() {
var src = '{% for i in (one..5) %}' +
'{% if i == 4 %}{% break %}{% endif %}' +
'{{ i }}' +
'{% endfor %}';
//return liquid.parseAndRender(src, ctx).catch(e => {
//console.log(e.stack);
//});
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('123');
});
'{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12345')
})
it('should support for with break', function () {
var src = '{% for i in (one..5) %}' +
'{% if i == 4 %}{% break %}{% endif %}' +
'{{ i }}' +
'{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('123')
})
it('should support for with limit', function() {
var src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12');
});
it('should support for with limit and offset', function() {
var src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('67');
});
describe('limit', function () {
it('should support for with limit', function () {
var src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12')
})
it('should support for with limit and offset', function () {
var src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('67')
})
})
it('should support for reversed', function() {
var src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21');
});
});
describe('reverse', function () {
it('should support for reversed in the last position', function () {
var src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21')
})
it('should support for reversed in the first position', function () {
var src = '{% for i in (1..5) reversed limit:2 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21')
})
it('should support for reversed in the middle position', function () {
var src = '{% for i in (1..5) offset:2 reversed limit:4 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('543')
})
})
})
+101 -47
View File
@@ -1,49 +1,103 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/if', function() {
var liquid = Liquid();
var ctx = {
one: 1,
two: 2,
emptyArray: []
};
describe('tags/if', function () {
var liquid = Liquid()
var ctx = {
one: 1,
two: 2,
emptyString: '',
emptyArray: []
}
it('should support if 1', function() {
var src = '{% if false%}yes';
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag {% if false%} not closed/);
});
it('should support if 2', function() {
var src = '{%if emptyArray%}a{%endif%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('');
});
it('should support if 3', function() {
var src = '{% if 2==3 %}yes{%else%}no{%endif%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no');
});
it('should support if 4', function() {
var src = '{% if 1>=2 and one<two %}a{%endif%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('');
});
it('should support if 5', function() {
var src = '{% if one!=two %}yes{%else%}no{%endif%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('yes');
});
it('should support if 6', function() {
var src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2');
});
it('should support if 7', function() {
var src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('');
});
});
it('should support if 1', function () {
var src = '{% if false%}yes'
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag {% if false%} not closed/)
})
it('should support if 2', function () {
var src = '{%if emptyArray%}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a')
})
it('should support if 3', function () {
var src = '{% if 2==3 %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should support if 4', function () {
var src = '{% if 1>=2 and one<two %}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('')
})
it('should support if 5', function () {
var src = '{% if one!=two %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('yes')
})
it('should support if 6', function () {
var src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2')
})
it('should support if 7', function () {
var src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('')
})
it('should return true if empty string', function () {
var src = '{%if emptyString%}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a')
})
it('should return else when comparison on null 1', function () {
var src = '{% if null < 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 2', function () {
var src = '{% if null <= 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 3', function () {
var src = '{% if null >= 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 4', function () {
var src = '{% if null > 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 5', function () {
var src = '{% if 10 < null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 6', function () {
var src = '{% if 10 <= null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 7', function () {
var src = '{% if 10 >= null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 8', function () {
var src = '{% if 10 > null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
})
+84 -85
View File
@@ -1,92 +1,91 @@
const Liquid = require('../..');
const mock = require('mock-fs');
const chai = require("chai");
const expect = chai.expect;
const ParseError = Liquid.Types.ParseError;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const mock = require('mock-fs')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/include', function() {
var liquid;
before(function() {
liquid = Liquid({
root: '/',
extname: '.html'
});
});
afterEach(function() {
mock.restore();
});
it('should support include', function() {
mock({
'/current.html': 'bar{% include "bar/foo.html" %}bar',
'/bar/foo.html': 'foo'
});
return expect(liquid.renderFile('/current.html')).to.
eventually.equal('barfoobar');
});
describe('tags/include', function () {
var liquid
before(function () {
liquid = Liquid({
root: '/',
extname: '.html'
})
})
afterEach(function () {
mock.restore()
})
it('should support include', function () {
mock({
'/current.html': 'bar{% include "bar/foo.html" %}bar',
'/bar/foo.html': 'foo'
})
return expect(liquid.renderFile('/current.html')).to
.eventually.equal('barfoobar')
})
it('should throw when illegal', function() {
mock({
'/illegal.html': '{%include%}',
});
return liquid.renderFile('/illegal.html').catch(function(e){
expect(e.name).to.equal('ParseError');
expect(e.message).to.match(/illegal token {%include%}/);
});
});
it('should throw when illegal', function () {
mock({
'/illegal.html': '{%include%}'
})
return liquid.renderFile('/illegal.html').catch(function (e) {
expect(e.name).to.equal('ParseError')
expect(e.message).to.match(/illegal token {%include%}/)
})
})
it('should support include with relative path', function() {
mock({
'/bar/foo.html': 'foo',
'/foo/relative.html': 'bar{% include "../bar/foo.html" %}bar',
});
return expect(liquid.renderFile('foo/relative.html')).to.
eventually.equal('barfoobar');
});
it('should support include with relative path', function () {
mock({
'/bar/foo.html': 'foo',
'/foo/relative.html': 'bar{% include "../bar/foo.html" %}bar'
})
return expect(liquid.renderFile('foo/relative.html')).to
.eventually.equal('barfoobar')
})
it('should support include: hash list', function() {
mock({
'/hash.html': '{% assign name="harttle" %}{% include "user.html", role: "admin", alias: name %}',
'/user.html': '{{name}} : {{role}} : {{alias}}',
});
return expect(liquid.renderFile('hash.html')).to.
eventually.equal('harttle : admin : harttle');
});
it('should support include: hash list', function () {
mock({
'/hash.html': '{% assign name="harttle" %}{% include "user.html", role: "admin", alias: name %}',
'/user.html': '{{name}} : {{role}} : {{alias}}'
})
return expect(liquid.renderFile('hash.html')).to
.eventually.equal('harttle : admin : harttle')
})
it('should support include: parent scope', function() {
mock({
'/scope.html': '{% assign shape="triangle" %}{% assign color="yellow" %}{% include "color.html" %}',
'/color.html': 'color:{{color}}, shape:{{shape}}',
});
return expect(liquid.renderFile('scope.html')).to.
eventually.equal('color:yellow, shape:triangle');
});
it('should support include: parent scope', function () {
mock({
'/scope.html': '{% assign shape="triangle" %}{% assign color="yellow" %}{% include "color.html" %}',
'/color.html': 'color:{{color}}, shape:{{shape}}'
})
return expect(liquid.renderFile('scope.html')).to
.eventually.equal('color:yellow, shape:triangle')
})
it('should support include: with', function() {
mock({
'/with.html': '{% include "color" with "red", shape: "rect" %}',
'/color.html': 'color:{{color}}, shape:{{shape}}',
});
return expect(liquid.renderFile('with.html')).to.
eventually.equal('color:red, shape:rect');
});
it('should support include: with', function () {
mock({
'/with.html': '{% include "color" with "red", shape: "rect" %}',
'/color.html': 'color:{{color}}, shape:{{shape}}'
})
return expect(liquid.renderFile('with.html')).to
.eventually.equal('color:red, shape:rect')
})
it('should support nested includes', function() {
mock({
'/personInfo.html': 'This is a person {% include "card.html" %}',
'/card.html': '<p>{{person.firstName}} {{person.lastName}}<br/>{% include "address" %}</p>',
'/address.html': 'City: {{person.address.city}}'
});
var ctx = {
person: {
firstName: 'Joe',
lastName: 'Shmoe',
address: {
city: 'Dallas'
}
}
};
return expect(liquid.renderFile('personInfo.html', ctx)).to.
eventually.equal('This is a person <p>Joe Shmoe<br/>City: Dallas</p>');
});
});
it('should support nested includes', function () {
mock({
'/personInfo.html': 'This is a person {% include "card.html" %}',
'/card.html': '<p>{{person.firstName}} {{person.lastName}}<br/>{% include "address" %}</p>',
'/address.html': 'City: {{person.address.city}}'
})
var ctx = {
person: {
firstName: 'Joe',
lastName: 'Shmoe',
address: {
city: 'Dallas'
}
}
}
return expect(liquid.renderFile('personInfo.html', ctx)).to
.eventually.equal('This is a person <p>Joe Shmoe<br/>City: Dallas</p>')
})
})
+28 -28
View File
@@ -1,32 +1,32 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/increment', function() {
var liquid = Liquid();
describe('tags/increment', function () {
var liquid = Liquid()
it('should support increment', function() {
var src = '{% increment one %}{{one}}';
var ctx = {
one: 1
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2');
});
it('should support increment', function () {
var src = '{% increment one %}{{one}}'
var ctx = {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2')
})
it('should increment undefined', function() {
var src = '{% increment empty %}{{empty}}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('1');
});
it('should increment undefined', function () {
var src = '{% increment empty %}{{empty}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('1')
})
it('should support increment multiple times', function() {
var src = '{% increment foo %}{%increment foo%}{{foo}}';
var ctx = {
foo: 1
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('3');
});
});
it('should support increment multiple times', function () {
var src = '{% increment foo %}{%increment foo%}{{foo}}'
var ctx = {
foo: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('3')
})
})
+87 -79
View File
@@ -1,81 +1,89 @@
const Liquid = require('../..');
const mock = require('mock-fs');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const mock = require('mock-fs')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/layout', function() {
var liquid;
before(function() {
liquid = Liquid({
root: '/',
extname: '.html'
});
});
afterEach(function() {
mock.restore();
});
describe('tags/layout', function () {
var liquid
before(function () {
liquid = Liquid({
root: '/',
extname: '.html'
})
})
afterEach(function () {
mock.restore()
})
it('should throw when block not closed', function() {
mock({
'/parent.html': 'parent',
});
src = '{% layout "parent" %}{%block%}A';
return expect(liquid.parseAndRender(src)).to
.be.rejectedWith(/tag {%block%} not closed/);
});
it('should handle anonymous block', function() {
mock({
'/parent.html': 'X{%block%}{%endblock%}Y',
});
src = '{% layout "parent.html" %}{%block%}A{%endblock%}';
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAY');
});
it('should handle named blocks', function() {
mock({
'/parent.html': 'X{% block "a"%}{% endblock %}Y{% block b%}{%endblock%}Z',
});
src = '{% layout "parent.html" %}' +
'{%block a%}A{%endblock%}' +
'{%block b%}B{%endblock%}';
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAYBZ');
});
it('should support default block content', function() {
mock({
'/parent.html': 'X{% block "a"%}A{% endblock %}Y{% block b%}B{%endblock%}Z',
});
src = '{% layout "parent.html" %}{%block a%}a{%endblock%}';
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XaYBZ');
});
it('should handle nested block', function() {
mock({
'/grand.html': 'X{%block a%}G{%endblock%}Y',
'/parent.html': '{%layout "grand" %}{%block a%}P{%endblock%}',
'/main.html': '{%layout "parent"%}{%block a%}A{%endblock%}'
})
return expect(liquid.renderFile('/main.html')).to
.eventually.equal('XAY');
});
it('should not bleed scope into included layout', function() {
mock({
'/parent.html': 'X{%block a%}{%endblock%}Y{%block b%}{%endblock%}Z',
'/main.html': '{%layout "parent"%}'+
'{%block a%}A{%endblock%}' +
'{%block b%}I{%include "included"%}J{%endblock%}',
'/included.html': '{%layout "parent"%}{%block a%}a{%endblock%}'
})
return expect(liquid.renderFile('main')).to
.eventually.equal('XAYIXaYZJZ');
});
it('should support hash list', function() {
mock({
'/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout "parent.html" color:"black"%}{%block%}A{%endblock%}'
});
return expect(liquid.renderFile('/main.html')).to.
eventually.equal('blackA');
});
});
it('should throw when block not closed', function () {
mock({
'/parent.html': 'parent'
})
var src = '{% layout "parent" %}{%block%}A'
return expect(liquid.parseAndRender(src)).to
.be.rejectedWith(/tag {%block%} not closed/)
})
it('should handle anonymous block', function () {
mock({
'/parent.html': 'X{%block%}{%endblock%}Y'
})
var src = '{% layout "parent.html" %}{%block%}A{%endblock%}'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAY')
})
it('should handle named blocks', function () {
mock({
'/parent.html': 'X{% block "a"%}{% endblock %}Y{% block b%}{%endblock%}Z'
})
var src = '{% layout "parent.html" %}' +
'{%block a%}A{%endblock%}' +
'{%block b%}B{%endblock%}'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAYBZ')
})
it('should support default block content', function () {
mock({
'/parent.html': 'X{% block "a"%}A{% endblock %}Y{% block b%}B{%endblock%}Z'
})
var src = '{% layout "parent.html" %}{%block a%}a{%endblock%}'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XaYBZ')
})
it('should handle nested block', function () {
mock({
'/grand.html': 'X{%block a%}G{%endblock%}Y',
'/parent.html': '{%layout "grand" %}{%block a%}P{%endblock%}',
'/main.html': '{%layout "parent"%}{%block a%}A{%endblock%}'
})
return expect(liquid.renderFile('/main.html')).to
.eventually.equal('XAY')
})
it('should not bleed scope into included layout', function () {
mock({
'/parent.html': 'X{%block a%}{%endblock%}Y{%block b%}{%endblock%}Z',
'/main.html': '{%layout "parent"%}' +
'{%block a%}A{%endblock%}' +
'{%block b%}I{%include "included"%}J{%endblock%}',
'/included.html': '{%layout "parent"%}{%block a%}a{%endblock%}'
})
return expect(liquid.renderFile('main')).to
.eventually.equal('XAYIXaYZJZ')
})
it('should support hash list', function () {
mock({
'/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout "parent.html" color:"black"%}{%block%}A{%endblock%}'
})
return expect(liquid.renderFile('/main.html')).to
.eventually.equal('blackA')
})
it('should support multiple hash', function () {
mock({
'/parent.html': '{{color}}{{bg}}{%block%}{%endblock%}',
'/main.html': '{% layout "parent.html" color:"black", bg:"red"%}{%block%}A{%endblock%}'
})
return expect(liquid.renderFile('/main.html')).to
.eventually.equal('blackredA')
})
})
+23 -23
View File
@@ -1,24 +1,24 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/raw', function() {
var liquid = Liquid();
it('should support raw 1', function() {
return expect(liquid.parseAndRender('{% raw%}'))
.to.be.rejectedWith(/{% raw%} not closed/);
});
it('should support raw 2', function() {
var src = '{% raw %}{{ 5 | plus: 6 }}{% endraw %} is equal to 11.';
var dst = '{{ 5 | plus: 6 }} is equal to 11.';
return expect(liquid.parseAndRender(src))
.to.eventually.equal(dst);
});
it('should support raw 3', function() {
var src = '{% raw %}\n{{ foo}} \n{% endraw %}';
var dst = '\n{{ foo}} \n';
return expect(liquid.parseAndRender(src))
.to.eventually.equal(dst);
});
});
describe('tags/raw', function () {
var liquid = Liquid()
it('should support raw 1', function () {
return expect(liquid.parseAndRender('{% raw%}'))
.to.be.rejectedWith(/{% raw%} not closed/)
})
it('should support raw 2', function () {
var src = '{% raw %}{{ 5 | plus: 6 }}{% endraw %} is equal to 11.'
var dst = '{{ 5 | plus: 6 }} is equal to 11.'
return expect(liquid.parseAndRender(src))
.to.eventually.equal(dst)
})
it('should support raw 3', function () {
var src = '{% raw %}\n{{ foo}} \n{% endraw %}'
var dst = '\n{{ foo}} \n'
return expect(liquid.parseAndRender(src))
.to.eventually.equal(dst)
})
})
+68 -62
View File
@@ -1,70 +1,76 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/tablerow', function() {
var liquid = Liquid();
describe('tags/tablerow', function () {
var liquid = Liquid()
it('should support tablerow', function() {
var src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}';
var ctx = {
alpha: ['a', 'b', 'c']
};
var dst = '<table>' +
'<tr class="row1"><td class="col1">a</td><td class="col2">b</td></tr>' +
'<tr class="row2"><td class="col1">c</td></tr>' +
'</table>';
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst);
});
it('should support tablerow', function () {
var src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}'
var ctx = {
alpha: ['a', 'b', 'c']
}
var dst = '<table>' +
'<tr class="row1"><td class="col1">a</td><td class="col2">b</td></tr>' +
'<tr class="row2"><td class="col1">c</td></tr>' +
'</table>'
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
})
it('should support empty tablerow', function() {
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}';
var dst = '<table></table>';
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst);
});
it('should support empty tablerow', function () {
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}'
var dst = '<table></table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should throw when tablerow not closed', function() {
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/);
});
it('should support empty array', function () {
var src = '{% tablerow i in alpha.z cols:2 %}{{ i }}{% endtablerow %}'
var dst = '<table></table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support tablerow with range', function() {
var src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}';
var dst = '<table>' +
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
'<tr class="row2"><td class="col1">3</td><td class="col2">4</td></tr>' +
'<tr class="row3"><td class="col1">5</td></tr>' +
'</table>';
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst);
});
it('should throw when tablerow not closed', function () {
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/)
})
it('tablerow should throw on illegal cols 1', function() {
var src = '{% tablerow i in (1..5) cols:0 %}{{ i }}{% endtablerow %}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/illegal cols: 0/);
});
it('tablerow should throw on illegal cols 2', function() {
var src = '{% tablerow i in (1..5) %}{{ i }}{% endtablerow %}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/illegal cols: undefined/);
});
it('should support tablerow with range', function () {
var src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}'
var dst = '<table>' +
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
'<tr class="row2"><td class="col1">3</td><td class="col2">4</td></tr>' +
'<tr class="row3"><td class="col1">5</td></tr>' +
'</table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support tablerow with limit', function() {
var src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}';
var dst = '<table>' +
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
'<tr class="row2"><td class="col1">3</td></tr>' +
'</table>';
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst);
});
it('tablerow should throw on illegal cols 1', function () {
var src = '{% tablerow i in (1..5) cols:0 %}{{ i }}{% endtablerow %}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/illegal cols: 0/)
})
it('tablerow should throw on illegal cols 2', function () {
var src = '{% tablerow i in (1..5) %}{{ i }}{% endtablerow %}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/illegal cols: undefined/)
})
it('should support tablerow with offset', function() {
var src = '{% tablerow i in (1..5) cols:2 offset:3 %}{{ i }}{% endtablerow %}';
var dst = '<table>' +
'<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>' +
'</table>';
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst);
});
});
it('should support tablerow with limit', function () {
var src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}'
var dst = '<table>' +
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
'<tr class="row2"><td class="col1">3</td></tr>' +
'</table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support tablerow with offset', function () {
var src = '{% tablerow i in (1..5) cols:2 offset:3 %}{{ i }}{% endtablerow %}'
var dst = '<table>' +
'<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>' +
'</table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
})
+33 -32
View File
@@ -1,34 +1,35 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/unless', function() {
var liquid = Liquid();
describe('tags/unless', function () {
var liquid = Liquid()
it('should render else when predicate yields true', function() {
var src = '{% unless 1 %}yes{%else%}no{%endunless%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('no');
});
it('should render unless when predicate yields false', function() {
var src = '{% unless 0 %}yes{%else%}no{%endunless%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes');
});
it('should reject when tag not closed', function() {
var src = '{% unless 1>2 %}yes';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag {% unless 1>2 %} not closed/);
});
it('should render unless when predicate yields false and else undefined', function() {
var src = '{% unless 1>2 %}yes{%endunless%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes');
});
it('should render "" when predicate yields false and else undefined', function() {
var src = '{% unless 1<2 %}yes{%endunless%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('');
});
});
it('should render else when predicate yields true', function () {
// 0 is truthy
var src = '{% unless 0 %}yes{%else%}no{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('no')
})
it('should render unless when predicate yields false', function () {
var src = '{% unless false %}yes{%else%}no{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes')
})
it('should reject when tag not closed', function () {
var src = '{% unless 1>2 %}yes'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag {% unless 1>2 %} not closed/)
})
it('should render unless when predicate yields false and else undefined', function () {
var src = '{% unless 1>2 %}yes{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes')
})
it('should render "" when predicate yields false and else undefined', function () {
var src = '{% unless 1<2 %}yes{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
})
+153 -51
View File
@@ -1,57 +1,159 @@
var chai = require("chai");
var should = chai.should();
var expect = chai.expect;
const chai = require('chai')
const parse = require('../src/tokenizer.js').parse
const whiteSpaceCtrl = require('../src/tokenizer.js').whiteSpaceCtrl
const expect = chai.expect
var tokenizer = require('../src/tokenizer.js');
describe('tokenizer', function () {
describe('parse', function () {
it('should handle plain HTML', function () {
var html = '<html><body><p>Lorem Ipsum</p></body></html>'
var tokens = parse(html)
describe('tokenizer', function() {
it('should handle plain HTML', function() {
var html = '<html><body><p>Lorem Ipsum</p></body></html>';
var tokens = tokenizer.parse(html);
expect(tokens.length).to.equal(1)
expect(tokens[0].value).to.equal(html)
expect(tokens[0].type).to.equal('html')
})
it('should throw when non-string passed in', function () {
expect(function () {
parse({})
}).to.throw('illegal input type')
})
it('should handle tag syntax', function () {
var html = '<p>{% for p in a[1]%}</p>'
var tokens = parse(html)
tokens.length.should.equal(1);
tokens[0].value.should.equal(html);
tokens[0].type.should.equal('html');
});
it('should throw when non-string passed in', function() {
expect(function() {
tokenizer.parse({});
}).to.throw('illegal input type');
});
it('should handle tag syntax', function() {
var html = '<p>{% for p in a[1]%}</p>';
var tokens = tokenizer.parse(html);
expect(tokens.length).to.equal(3)
expect(tokens[1].type).to.equal('tag')
expect(tokens[1].value).to.equal('for p in a[1]')
})
it('should handle output syntax', function () {
var html = '<p>{{foo | date: "%Y-%m-%d"}}</p>'
var tokens = parse(html)
tokens.length.should.equal(3);
tokens[1].type.should.equal('tag');
tokens[1].value.should.equal('for p in a[1]');
});
it('should handle output syntax', function() {
var html = '<p>{{foo | date: "%Y-%m-%d"}}</p>';
var tokens = tokenizer.parse(html);
expect(tokens.length).to.equal(3)
expect(tokens[1].type).to.equal('output')
expect(tokens[1].value).to.equal('foo | date: "%Y-%m-%d"')
})
it('should handle successive outputs and tags', function () {
var html = '{{foo}}{{bar}}{%foo%}{%bar%}'
var tokens = parse(html)
tokens.length.should.equal(3);
tokens[1].type.should.equal('output');
tokens[1].value.should.equal('foo | date: "%Y-%m-%d"');
});
it('should handle successive outputs and tags', function() {
var html = '{{foo}}{{bar}}{%foo%}{%bar%}';
var tokens = tokenizer.parse(html);
expect(tokens.length).to.equal(4)
expect(tokens[0].type).to.equal('output')
expect(tokens[3].type).to.equal('tag')
tokens.length.should.equal(4);
tokens[0].type.should.equal('output');
tokens[3].type.should.equal('tag');
tokens[1].value.should.equal('bar');
tokens[2].value.should.equal('foo');
});
it('should keep white spaces and newlines', function() {
var html = '{{foo}}\n{%bar %} \n {{alice}}';
var tokens = tokenizer.parse(html);
expect(tokens.length).to.equal(5);
expect(tokens[1].type).to.equal('html');
expect(tokens[1].raw).to.equal('\n');
expect(tokens[3].type).to.equal('html');
expect(tokens[3].raw).to.equal(' \n ');
});
});
expect(tokens[1].value).to.equal('bar')
expect(tokens[2].value).to.equal('foo')
})
it('should keep white spaces and newlines', function () {
var html = '{%foo%}\n{%bar %} \n {%alice%}'
var tokens = parse(html)
expect(tokens.length).to.equal(5)
expect(tokens[1].type).to.equal('html')
expect(tokens[1].raw).to.equal('\n')
expect(tokens[3].type).to.equal('html')
expect(tokens[3].raw).to.equal(' \n ')
})
it('should handle multiple lines tag', function () {
var html = '{%foo\na:a\nb:1.23\n%}'
var tokens = parse(html)
expect(tokens.length).to.equal(1)
expect(tokens[0].type).to.equal('tag')
expect(tokens[0].args).to.equal('a:a\nb:1.23')
expect(tokens[0].raw).to.equal('{%foo\na:a\nb:1.23\n%}')
})
it('should handle multiple lines output', function () {
var html = '{{foo\n|date:\n"%Y-%m-%d"\n}}'
var tokens = parse(html)
expect(tokens.length).to.equal(1)
expect(tokens[0].type).to.equal('output')
expect(tokens[0].raw).to.equal('{{foo\n|date:\n"%Y-%m-%d"\n}}')
})
})
describe('whitespace control', function () {
it('should not strip by default (tag)', function () {
expect(whiteSpaceCtrl('\n {%foo%} \n')).to.equal('\n {%foo%} \n')
})
it('should strip all blank characters before and after (tag)', function () {
expect(whiteSpaceCtrl(' \t\r{%-foo-%} \t\n')).to.equal('{%-foo-%}')
})
it('should not trim previous/next lines (tag)', function () {
expect(whiteSpaceCtrl(' \t\n {%-foo-%}')).to.equal(' \t\n{%-foo-%}')
expect(whiteSpaceCtrl('{%-foo-%} \n \tfoo')).to.equal('{%-foo-%} \tfoo')
})
it('should trim exactly one trailing CR (tag)', function () {
expect(whiteSpaceCtrl('{%-foo-%} \n\n')).to.equal('{%-foo-%}\n')
})
it('should trim exactly one trailing CR (tag)', function () {
expect(whiteSpaceCtrl('{%-foo-%} \n\n')).to.equal('{%-foo-%}\n')
})
it('should trim all leading/trailing blanks when options.greedy set (tag)', function () {
expect(whiteSpaceCtrl(' \n \n\t\r{%-foo-%}\n \n', {
greedy: true
})).to.equal('{%-foo-%}')
})
it('should strip whitespaces when set trim_left (tag)', function () {
expect(whiteSpaceCtrl('\n {%foo%} \n', {
trim_left: true
})).to.equal('\n{%-foo%} \n')
})
it('should strip whitespaces when set trim_right (tag)', function () {
expect(whiteSpaceCtrl('\n {%foo%} \n', {
trim_right: true
})).to.equal('\n {%foo-%}')
})
it('markup should has priority over options (tag)', function () {
expect(whiteSpaceCtrl('\n {%-foo%} \n', {
trim_left: false
})).to.equal('\n{%-foo%} \n')
})
it('should support a mix of markup and options (tag)', function () {
expect(whiteSpaceCtrl(' {%-foo%} \n', {
trim_left: true,
trim_right: true
})).to.equal('{%-foo-%}')
})
it('should not strip by default (value)', function () {
expect(whiteSpaceCtrl('\n {{foo}} \n')).to.equal('\n {{foo}} \n')
})
it('should strip all blank characters before and after (value)', function () {
expect(whiteSpaceCtrl(' \t\r{{-foo-}} \t\n')).to.equal('{{-foo-}}')
})
it('should not trim previous/next lines (value)', function () {
expect(whiteSpaceCtrl(' \t\n {{-foo-}}')).to.equal(' \t\n{{-foo-}}')
expect(whiteSpaceCtrl('{{-foo-}} \n \tfoo')).to.equal('{{-foo-}} \tfoo')
})
it('should trim exactly one trailing CR (value)', function () {
expect(whiteSpaceCtrl('{{-foo-}} \n\n')).to.equal('{{-foo-}}\n')
})
it('should trim exactly one trailing CR (value)', function () {
expect(whiteSpaceCtrl('{{-foo-}} \n\n')).to.equal('{{-foo-}}\n')
})
it('should trim all leading/trailing blanks when options.greedy set (value)', function () {
expect(whiteSpaceCtrl(' \n \n\t\r{{-foo-}}\n \n', {
greedy: true
})).to.equal('{{-foo-}}')
})
it('should strip whitespaces when set trim_left (value)', function () {
expect(whiteSpaceCtrl('\n {{foo}} \n', {
trim_left: true
})).to.equal('\n{{-foo}} \n')
})
it('should strip whitespaces when set trim_right (value)', function () {
expect(whiteSpaceCtrl('\n {{foo}} \n', {
trim_right: true
})).to.equal('\n {{foo-}}')
})
it('markup should has priority over options (value)', function () {
expect(whiteSpaceCtrl('\n {{-foo}} \n', {
trim_left: false
})).to.equal('\n{{-foo}} \n')
})
it('should support a mix of markup and options (value)', function () {
expect(whiteSpaceCtrl(' {{-foo}} \n', {
trim_left: true,
trim_right: true
})).to.equal('{{-foo-}}')
})
})
})
+18
View File
@@ -0,0 +1,18 @@
const chai = require('chai')
const expect = chai.expect
const assert = require('../../src/util/assert.js')
describe('assert', function () {
it('should not throw if predicate is truthy', function () {
var fn = () => assert('foo', 'bar')
expect(fn).to.not.throw()
})
it('should not throw if predicate is truthy', function () {
var fn = () => assert('', 'bar')
expect(fn).to.throw(/bar/)
})
it('should populate default message', function () {
var fn = () => assert(false)
expect(fn).to.throw(/expect false to be true/)
})
})
+377 -313
View File
@@ -1,326 +1,390 @@
const chai = require("chai");
const expect = chai.expect;
const mock = require('mock-fs');
chai.use(require("chai-as-promised"));
const chai = require('chai')
const expect = chai.expect
const mock = require('mock-fs')
chai.use(require('chai-as-promised'))
var engine = require('../..')();
var engine = require('../..')()
var strictEngine = require('../..')({
strict_variables: true,
strict_filters: true
});
strict_variables: true,
strict_filters: true
})
describe('error', function() {
describe('error', function () {
afterEach(function () {
mock.restore()
})
describe('TokenizationError', function() {
it('should throw TokenizationError when tag illegal', function() {
return expect(engine.parseAndRender('{% . a %}', {})).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('TokenizationError');
expect(err.message).to.contain('illegal tag syntax');
});
});
it('should contain template content in err.message', function() {
var html = ['1st', '2nd', 'X{% . a %} Y', '4th'];
var message = [
' 1| 1st',
' 2| 2nd',
'>> 3| X{% . a %} Y',
' 4| 4th',
'TokenizationError: illegal tag syntax',
];
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.be.rejected
.then(function(err) {
expect(err.message).to.equal('illegal tag syntax, line:3');
expect(err.stack).to.contain(message.join('\n'));
expect(err.name).to.equal('TokenizationError');
});
});
it('should contain the whole template content in err.input', function() {
var html = 'bar\nfoo{% . a %}\nfoo';
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function(err) {
expect(err.input).to.equal(html);
});
});
it('should contain line number in err.line', function() {
return expect(engine.parseAndRender('1\n2\n{% . a %}\n4', {})).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('TokenizationError');
expect(err.line).to.equal(3);
});
});
it('should contain stack in err.stack', function() {
return expect(engine.parseAndRender('{% . a %}')).to.eventually
.be.rejected
.then(function(err) {
expect(err.stack).to.contain('illegal tag syntax');
expect(err.stack).to.contain('at Object.parse');
});
});
it('should contain file path in err.file', function() {
var html = '<html>\n<head>\n\n{% . a %}\n\n';
mock({
"/foo.html": html
});
return expect(engine.renderFile('/foo.html')).to.eventually
.be.rejected
.then(function(err) {
mock.restore();
expect(err.name).to.equal('TokenizationError');
expect(err.file).to.equal('/foo.html');
});
});
});
describe('TokenizationError', function () {
it('should throw TokenizationError when tag illegal', function () {
return expect(engine.parseAndRender('{% . a %}', {})).to.eventually
.be.rejected
.then(function (err) {
expect(err.name).to.equal('TokenizationError')
expect(err.message).to.contain('illegal tag syntax')
})
})
it('should contain template content in err.message', function () {
var html = ['1st', '2nd', 'X{% . a %} Y', '4th']
var message = [
' 1| 1st',
' 2| 2nd',
'>> 3| X{% . a %} Y',
' 4| 4th',
'TokenizationError'
]
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.be.rejected
.then(function (err) {
expect(err.message).to.equal('illegal tag syntax, line:3')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('TokenizationError')
})
})
it('should contain the whole template content in err.input', function () {
var html = 'bar\nfoo{% . a %}\nfoo'
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function (err) {
expect(err.input).to.equal(html)
})
})
it('should contain line number in err.line', function () {
return expect(engine.parseAndRender('1\n2\n{% . a %}\n4', {})).to.eventually
.be.rejected
.then(function (err) {
expect(err.name).to.equal('TokenizationError')
expect(err.line).to.equal(3)
})
})
it('should contain stack in err.stack', function () {
return expect(engine.parseAndRender('{% . a %}')).to.eventually
.be.rejected
.then(function (err) {
expect(err.message).to.contain('illegal tag syntax')
expect(err.stack).to.contain('at Object.parse')
})
})
describe('captureStackTrace compatibility', function () {
var captureStackTrace = Error.captureStackTrace
before(() => (Error.captureStackTrace = null))
after(() => (Error.captureStackTrace = captureStackTrace))
it('should use empty string if captureStackTrace not defined', function () {
return expect(engine.parseAndRender('{% . a %}')).to.eventually
.be.rejected
.then(function (err) {
expect(err.stack).to.contain('illegal tag syntax')
expect(err.stack).to.not.contain('at Object.parse')
})
})
})
it('should contain file path in err.file', function () {
var html = '<html>\n<head>\n\n{% . a %}\n\n'
mock({
'/foo.html': html
})
return expect(engine.renderFile('/foo.html')).to.eventually
.be.rejected
.then(function (err) {
mock.restore()
expect(err.name).to.equal('TokenizationError')
expect(err.file).to.equal('/foo.html')
})
})
})
describe('RenderError', function() {
beforeEach(function() {
engine = require('../..')();
engine.registerTag('throwingTag', {
render: function() {
throw new Error('intended render error');
}
});
engine.registerTag('rejectingTag', {
render: function() {
return Promise.reject(new Error('intended render reject'));
}
});
engine.registerFilter('throwingFilter', () => {
throw new Error('throwed by filter');
});
});
it('should throw RenderError when tag throws', function() {
var src = '{%throwingTag%}';
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('RenderError');
expect(err.message).to.contain('intended render error');
});
});
it('should throw RenderError when tag rejects', function() {
var src = '{%rejectingTag%}';
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('RenderError');
expect(err.message).to.contain('intended render reject');
});
});
it('should throw RenderError when filter throws', function() {
var src = '{{1|throwingFilter}}';
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('RenderError');
expect(err.message).to.contain('throwed by filter');
});
});
it('should not throw when variable undefined by default', function() {
return expect(engine.parseAndRender('X{{a}}Y')).to.eventually.equal('XY');
});
it('should throw RenderError when variable not defined', function() {
return expect(strictEngine.parseAndRender('{{a}}')).to.eventually
.be.rejected
.then(function(e) {
expect(e).to.have.property('name', 'RenderError');
expect(e.message).to.contain('undefined variable: a');
});
});
it('should contain template content in err.message', function() {
var html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th'];
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'Error: intended render error',
];
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.be.rejected
.then(function(err) {
expect(err.message).to.equal('intended render error, line:4');
expect(err.stack).to.contain(message.join('\n'));
expect(err.name).to.equal('RenderError');
});
});
it('should contain the whole template content in err.input', function() {
var html = 'bar\nfoo{%throwingTag%}\nfoo';
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function(err) {
expect(err.input).to.equal(html);
expect(err.name).to.equal('RenderError');
});
});
it('should contain line number in err.line', function() {
var src = '1\n2\n{{1|throwingFilter}}\n4';
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function(err) {
expect(err.line).to.equal(3);
expect(err.name).to.equal('RenderError');
});
});
it('should contain stack in err.stack', function() {
return expect(engine.parseAndRender('{%rejectingTag%}')).to.eventually
.be.rejected
.then(function(err) {
expect(err.stack).to.contain('intended render reject');
expect(err.stack).to.contain('at Object.engine.registerTag.render');
});
});
describe('RenderError', function () {
beforeEach(function () {
engine = require('../..')({
root: '/'
})
engine.registerTag('throwingTag', {
render: function () {
throw new Error('intended render error')
}
})
engine.registerTag('rejectingTag', {
render: function () {
return Promise.reject(new Error('intended render reject'))
}
})
engine.registerFilter('throwingFilter', () => {
throw new Error('throwed by filter')
})
})
it('should throw RenderError when tag throws', function () {
var src = '{%throwingTag%}'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function (err) {
expect(err.name).to.equal('RenderError')
expect(err.message).to.contain('intended render error')
})
})
it('should throw RenderError when tag rejects', function () {
var src = '{%rejectingTag%}'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function (err) {
expect(err.name).to.equal('RenderError')
expect(err.message).to.contain('intended render reject')
})
})
it('should throw RenderError when filter throws', function () {
var src = '{{1|throwingFilter}}'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function (err) {
expect(err.name).to.equal('RenderError')
expect(err.message).to.contain('throwed by filter')
})
})
it('should not throw when variable undefined by default', function () {
return expect(engine.parseAndRender('X{{a}}Y')).to.eventually.equal('XY')
})
it('should throw RenderError when variable not defined', function () {
return expect(strictEngine.parseAndRender('{{a}}')).to.eventually
.be.rejected
.then(function (e) {
expect(e).to.have.property('name', 'RenderError')
expect(e.message).to.contain('undefined variable: a')
})
})
it('should contain template context in err.stack', function () {
var html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'RenderError'
]
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.be.rejected
.then(function (err) {
expect(err.message).to.equal('intended render error, line:4')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('RenderError')
})
})
it('should contain original error info for {% layout %}', function () {
mock({
'/throwing-tag.html': [
'1st',
'2nd',
'3rd',
'X{%throwingTag%} Y',
'5th',
'{%block%}{%endblock%}',
'7th'
].join('\n')
})
var html = '{%layout "throwing-tag.html"%}'
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| {%block%}{%endblock%}',
' 7| 7th',
'RenderError'
]
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function (err) {
console.log(err.message)
console.log(err.stack)
expect(err.message).to.equal('intended render error, file:/throwing-tag.html, line:4')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('RenderError')
})
})
it('should contain original error info for {% include %}', function () {
var origin = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
mock({
'/throwing-tag.html': origin.join('\n')
})
var html = '{%include "throwing-tag.html"%}'
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'RenderError'
]
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function (err) {
expect(err.message).to.equal('intended render error, file:/throwing-tag.html, line:4')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('RenderError')
})
})
it('should contain the whole template content in err.input', function () {
var html = 'bar\nfoo{%throwingTag%}\nfoo'
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function (err) {
expect(err.input).to.equal(html)
expect(err.name).to.equal('RenderError')
})
})
it('should contain line number in err.line', function () {
var src = '1\n2\n{{1|throwingFilter}}\n4'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function (err) {
expect(err.line).to.equal(3)
expect(err.name).to.equal('RenderError')
})
})
it('should contain stack in err.stack', function () {
return expect(engine.parseAndRender('{%rejectingTag%}')).to.eventually
.be.rejected
.then(function (err) {
expect(err.message).to.contain('intended render reject')
expect(err.stack).to.match(/at .*:\d+:\d+/)
})
})
it('should contain file path in err.file', function() {
var html = '<html>\n<head>\n\n{% throwingTag %}\n\n';
mock({
"/foo.html": html
});
return expect(engine.renderFile('/foo.html')).to.eventually
.be.rejected
.then(function(err) {
mock.restore();
expect(err.name).to.equal('RenderError');
expect(err.file).to.equal('/foo.html');
});
});
});
it('should contain file path in err.file', function () {
var html = '<html>\n<head>\n\n{% throwingTag %}\n\n'
mock({
'/foo.html': html
})
return expect(engine.renderFile('/foo.html')).to.eventually
.be.rejected
.then(function (err) {
mock.restore()
expect(err.name).to.equal('RenderError')
expect(err.file).to.equal('/foo.html')
})
})
})
describe('ParseError', function() {
beforeEach(function() {
engine = require('../..')();
engine.registerTag('throwsOnParse', {
parse: function() {
throw new Error('intended parse error');
}
});
});
it('should throw RenderError when filter not defined', function() {
return expect(strictEngine.parseAndRender('{{1 | a}}')).to.eventually
.be.rejected
.then(function(e) {
expect(e).to.have.property('name', 'ParseError');
expect(e.message).to.contain('undefined filter: a');
});
});
it('should throw ParseError when tag not closed', function() {
return expect(engine.parseAndRender('{% if %}')).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('ParseError');
expect(err.message).to.contain('tag {% if %} not closed');
});
});
it('should throw ParseError when tag parse throws', function() {
var src = '{%throwsOnParse%}';
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('ParseError');
expect(err.message).to.contain('intended parse error');
});
});
it('should throw ParseError when tag not found', function() {
var src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3';
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('ParseError');
expect(err.message).to.contain('tag -a not found');
});
});
describe('ParseError', function () {
beforeEach(function () {
engine = require('../..')()
engine.registerTag('throwsOnParse', {
parse: function () {
throw new Error('intended parse error')
}
})
})
it('should throw RenderError when filter not defined', function () {
return expect(strictEngine.parseAndRender('{{1 | a}}')).to.eventually
.be.rejected
.then(function (e) {
expect(e).to.have.property('name', 'ParseError')
expect(e.message).to.contain('undefined filter: a')
})
})
it('should throw ParseError when tag not closed', function () {
return expect(engine.parseAndRender('{% if %}')).to.eventually
.be.rejected
.then(function (err) {
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag {% if %} not closed')
})
})
it('should throw ParseError when tag parse throws', function () {
var src = '{%throwsOnParse%}'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function (err) {
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('intended parse error')
})
})
it('should throw ParseError when tag not found', function () {
var src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function (err) {
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag -a not found')
})
})
it('should throw ParseError when tag not exist', function() {
return expect(engine.parseAndRender('{% a %}')).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('ParseError');
expect(err.message).to.contain('tag a not found');
});
});
it('should throw ParseError when tag not exist', function () {
return expect(engine.parseAndRender('{% a %}')).to.eventually
.be.rejected
.then(function (err) {
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag a not found')
})
})
it('should contain template content in err.message', function() {
var html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th'];
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{% a %} {% enda %} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'AssertionError: tag a not found',
];
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.be.rejected
.then(function(err) {
expect(err.message).to.equal('tag a not found, line:4');
expect(err.stack).to.contain(message.join('\n'));
expect(err.name).to.equal('ParseError');
});
});
it('should contain template context in err.stack', function () {
var html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th']
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{% a %} {% enda %} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'ParseError: tag a not found'
]
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.be.rejected
.then(function (err) {
expect(err.message).to.equal('tag a not found, line:4')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('ParseError')
})
})
it('should handle err.message when context not enough', function() {
var html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th'];
var message = [
' 1| 1st',
'>> 2| X{% a %} {% enda %} Y',
' 3| 3rd',
' 4| 4th',
'AssertionError: tag a not found',
];
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.be.rejected
.then(function(err) {
expect(err.message).to.equal('tag a not found, line:2');
expect(err.stack).to.contain(message.join('\n'));
});
});
it('should handle err.message when context not enough', function () {
var html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th']
var message = [
' 1| 1st',
'>> 2| X{% a %} {% enda %} Y',
' 3| 3rd',
' 4| 4th',
'ParseError: tag a not found'
]
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.be.rejected
.then(function (err) {
expect(err.message).to.equal('tag a not found, line:2')
expect(err.stack).to.contain(message.join('\n'))
})
})
it('should contain the whole template content in err.input', function() {
var html = 'bar\nfoo{% a %}\nfoo';
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function(err) {
expect(err.input).to.equal(html);
});
});
it('should contain line number in err.line', function () {
var html = '<html>\n<head>\n\n{% raw %}\n\n'
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function (err) {
expect(err.line).to.equal(4)
})
})
it('should contain line number in err.line', function() {
var html = '<html>\n<head>\n\n{% raw %}\n\n';
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function(err) {
expect(err.line).to.equal(4);
});
});
it('should contain stack in err.stack', function () {
return expect(engine.parseAndRender('{% -a %}')).to.eventually
.be.rejected
.then(function (err) {
expect(err.stack).to.contain('ParseError: tag -a not found')
expect(err.stack).to.match(/at .*:\d+:\d+\)/)
})
})
it('should contain stack in err.stack', function() {
return expect(engine.parseAndRender('{% -a %}')).to.eventually
.be.rejected
.then(function(err) {
expect(err.stack).to.contain('AssertionError: tag -a not found');
expect(err.stack).to.contain('at Object._tagInstance.parse');
});
});
it('should contain file path in err.file', function() {
var html = '<html>\n<head>\n\n{% raw %}\n\n';
mock({
"/foo.html": html
});
return expect(engine.renderFile('/foo.html')).to.eventually
.be.rejected
.then(function(err) {
mock.restore();
expect(err.name).to.equal('ParseError');
expect(err.file).to.equal('/foo.html');
});
});
});
});
it('should contain file path in err.file', function () {
var html = '<html>\n<head>\n\n{% raw %}\n\n'
mock({
'/foo.html': html
})
return expect(engine.renderFile('/foo.html')).to.eventually
.be.rejected
.then(function (err) {
mock.restore()
expect(err.name).to.equal('ParseError')
expect(err.file).to.equal('/foo.html')
})
})
})
})
+92 -90
View File
@@ -1,92 +1,94 @@
const chai = require("chai");
const sinon = require('sinon');
const expect = chai.expect;
chai.use(require("chai-as-promised"));
chai.use(require("sinon-chai"));
const chai = require('chai')
const sinon = require('sinon')
const expect = chai.expect
chai.use(require('chai-as-promised'))
chai.use(require('sinon-chai'))
var P = require('../../src/util/promise.js');
var P = require('../../src/util/promise.js')
describe('util/promise', function() {
describe('.anySeries()', function() {
it('should resolve in series', function() {
var spy1 = sinon.spy(),
spy2 = sinon.spy();
return P
.anySeries(
['first', 'second'],
(item, idx) => new Promise(function(resolve, reject) {
if (idx === 0) {
setTimeout(function() {
spy1();
reject(new Error('first cb'));
}, 10);
} else {
spy2();
resolve('foo');
}
}))
.then(() => expect(spy2).to.have.been.calledAfter(spy1));
});
it('should reject when all rejected', function() {
var p = P.anySeries(['first', 'second', 'third'],
item => Promise.reject(new Error(item)));
return expect(p).to.be.rejectedWith("third");
});
it('should resolve the value that first callback resolved', () => {
var p = P.anySeries(['first', 'second'],
item => Promise.resolve(item));
return expect(p).to.eventually.equal('first');
});
it('should not call rest of callbacks once resolved', () => {
var spy = sinon.spy();
return P.anySeries(['first', 'second'], (item, idx) => {
if (idx > 0) {
spy();
}
return Promise.resolve(item);
})
.then(() => expect(spy).to.not.have.been.called);
});
});
describe('.mapSeries()', function() {
it('should resolve when all resolved', function() {
var p = P.mapSeries(['first', 'second', 'third'],
item => Promise.resolve(item));
return expect(p).to.eventually.deep.equal(['first', 'second', "third"]);
});
it('should reject with the error that first callback rejected', () => {
var p = P.mapSeries(['first', 'second'],
item => Promise.reject(item));
return expect(p).to.rejectedWith('first');
});
it('should resolve in series', function() {
var spy1 = sinon.spy(),
spy2 = sinon.spy();
return P
.mapSeries(
['first', 'second'],
(item, idx) => new Promise(function(resolve, reject) {
if (idx === 0) {
setTimeout(function() {
spy1();
resolve('first cb');
}, 10);
} else {
spy2();
resolve('foo');
}
}))
.then(() => expect(spy2).to.have.been.calledAfter(spy1));
});
it('should not call rest of callbacks once rejected', () => {
var spy = sinon.spy();
return P.mapSeries(['first', 'second'], (item, idx) => {
if (idx > 0) {
spy();
}
return Promise.reject(new Error(item));
})
.catch(() => expect(spy).to.not.have.been.called);
});
});
});
describe('util/promise', function () {
describe('.anySeries()', function () {
it('should resolve in series', function () {
var spy1 = sinon.spy()
var spy2 = sinon.spy()
return P
.anySeries(
['first', 'second'],
(item, idx) => new Promise(function (resolve, reject) {
if (idx === 0) {
setTimeout(function () {
spy1()
reject(new Error('first cb'))
}, 10)
} else {
spy2()
resolve('foo')
}
}))
.then(() => expect(spy2).to.have.been.calledAfter(spy1))
})
it('should reject when all rejected', function () {
var p = P.anySeries(['first', 'second', 'third'],
item => Promise.reject(new Error(item)))
return expect(p).to.be.rejectedWith('third')
})
it('should resolve the value that first callback resolved', () => {
var p = P.anySeries(['first', 'second'],
item => Promise.resolve(item))
return expect(p).to.eventually.equal('first')
})
it('should not call rest of callbacks once resolved', () => {
var spy = sinon.spy()
return P
.anySeries(['first', 'second'], (item, idx) => {
if (idx > 0) {
spy()
}
return Promise.resolve(item)
})
.then(() => expect(spy).to.not.have.been.called)
})
})
describe('.mapSeries()', function () {
it('should resolve when all resolved', function () {
var p = P.mapSeries(['first', 'second', 'third'],
item => Promise.resolve(item))
return expect(p).to.eventually.deep.equal(['first', 'second', 'third'])
})
it('should reject with the error that first callback rejected', () => {
var p = P.mapSeries(['first', 'second'],
item => Promise.reject(item))
return expect(p).to.rejectedWith('first')
})
it('should resolve in series', function () {
var spy1 = sinon.spy()
var spy2 = sinon.spy()
return P
.mapSeries(
['first', 'second'],
(item, idx) => new Promise(function (resolve, reject) {
if (idx === 0) {
setTimeout(function () {
spy1()
resolve('first cb')
}, 10)
} else {
spy2()
resolve('foo')
}
}))
.then(() => expect(spy2).to.have.been.calledAfter(spy1))
})
it('should not call rest of callbacks once rejected', () => {
var spy = sinon.spy()
return P
.mapSeries(['first', 'second'], (item, idx) => {
if (idx > 0) {
spy()
}
return Promise.reject(new Error(item))
})
.catch(() => expect(spy).to.not.have.been.called)
})
})
})
+136 -110
View File
@@ -1,120 +1,146 @@
const chai = require("chai");
const expect = chai.expect;
const chai = require('chai')
const expect = chai.expect
var t = require('../../src/util/strftime.js');
var t = require('../../src/util/strftime.js')
describe('util/strftime', function() {
var now;
before(function() {
mockUTC();
now = new Date('2016-01-04T13:15:23');
then = new Date('2016-03-06T03:05:03');
});
after(function() {
restoreUTC();
});
describe('util/strftime', function () {
var now
var then
before(function () {
mockUTC()
now = new Date('2016-01-04T13:15:23.000Z')
then = new Date('2016-03-06T03:05:03.000Z')
})
after(function () {
restoreUTC()
})
it('should format UTC datetime', function() {
expect(t(now, '%Y-%m-%dT%H:%M:%S')).to.equal('2016-01-04T13:15:23');
});
it('should format %A as Monday', function() {
expect(t(now, '%A')).to.equal('Monday');
});
it('should format %B as month name', function() {
expect(t(now, '%B')).to.equal('January');
});
it('should format %C as century', function() {
expect(t(now, '%C')).to.equal('20');
});
it('should format %c as local string', function() {
expect(t(now, '%c')).to.equal(now.toLocaleString());
});
it('should format %e as space padded date', function() {
expect(t(now, '%e')).to.equal(' 4');
});
it('should format %I as 0 padded hour12', function() {
expect(t(now, '%I')).to.equal('01');
});
it('should format %j as day of year', function() {
expect(t(then, '%j')).to.equal('066');
});
it('should format %k as space padded hour', function() {
expect(t(then, '%k')).to.equal(' 3');
});
it('should format %l as space padded hour12', function() {
expect(t(now, '%l')).to.equal(' 1');
});
it('should format %L as 0 padded millisecond', function() {
expect(t(then, '%L')).to.equal('000');
});
it('should format %p as upper cased am/pm', function() {
expect(t(now, '%p')).to.equal('PM');
expect(t(then, '%p')).to.equal('AM');
});
it('should format %P as lower cased am/pm', function() {
expect(t(now, '%P')).to.equal('pm');
expect(t(then, '%P')).to.equal('am');
});
it('should format %q as date suffix', function(){
var st = new Date('2016-03-01T03:05:03');
var nd = new Date('2016-03-02T03:05:03');
var rd = new Date('2016-03-03T03:05:03');
expect(t(st, '%q')).to.equal('st');
expect(t(nd, '%q')).to.equal('nd');
expect(t(rd, '%q')).to.equal('rd');
expect(t(now, '%q')).to.equal('th');
});
it('should format %s as UNIX seconds', function(){
expect(t(now, '%s')).to.be.match(/\d+/);
});
it('should format %u as day of week(1-7)', function(){
expect(t(now, '%u')).to.be.equal('1');
expect(t(then, '%u')).to.be.equal('7');
});
it('should format %U as week of year, starts with 0', function() {
expect(t(now, '%U')).to.equal('01');
});
it('should format %w as day of month(0-7)', function(){
expect(t(now, '%w')).to.be.equal('1');
expect(t(then, '%w')).to.be.equal('0');
});
it('should format %W as week of year, starts with 1', function(){
expect(t(now, '%W')).to.be.equal('01');
});
it('should format %x as local date string', function() {
expect(t(now, '%x')).to.equal(now.toLocaleDateString());
});
it('should format %X as local time string', function() {
expect(t(now, '%X')).to.equal(now.toLocaleTimeString());
});
it('should format %y as 2-digit year', function() {
expect(t(now, '%y')).to.equal('16');
});
it('should format %z as time zone', function() {
expect(t(now, '%z')).to.equal('+0800');
});
it('should escape %% as %', function() {
expect(t(now, '%%')).to.equal('%');
});
});
it('should format UTC datetime', function () {
expect(t(now, '%Y-%m-%dT%H:%M:%S')).to.equal('2016-01-04T13:15:23')
})
it('should format %A as Monday', function () {
expect(t(now, '%A')).to.equal('Monday')
})
it('should format %B as month name', function () {
expect(t(now, '%B')).to.equal('January')
})
it('should format %C as century', function () {
expect(t(now, '%C')).to.equal('20')
})
it('should format %c as local string', function () {
expect(t(now, '%c')).to.equal(now.toLocaleString())
})
it('should format %e as space padded date', function () {
expect(t(now, '%e')).to.equal(' 4')
})
it('should format %I as 0 padded hour12', function () {
expect(t(now, '%I')).to.equal('01')
})
it('should format %I as 12 for 00:00', function () {
var date = new Date('2016-01-01T00:00:00.000Z')
expect(t(date, '%I')).to.equal('12')
})
describe('%j', function () {
it('should format %j as day of year', function () {
expect(t(then, '%j')).to.equal('066')
})
it('should take count of leap years', function () {
var date = new Date('2001-03-01')
expect(t(date, '%j')).to.equal('060')
})
it('should take count of leap years', function () {
var date = new Date('2000-03-01')
expect(t(date, '%j')).to.equal('061')
})
})
it('should format %k as space padded hour', function () {
expect(t(then, '%k')).to.equal(' 3')
})
it('should format %l as space padded hour12', function () {
expect(t(now, '%l')).to.equal(' 1')
})
it('should format %l as 12 for 00:00', function () {
var date = new Date('2016-01-01T00:00:00.000Z')
expect(t(date, '%l')).to.equal('12')
})
it('should format %L as 0 padded millisecond', function () {
expect(t(then, '%L')).to.equal('000')
})
it('should format %p as upper cased am/pm', function () {
expect(t(now, '%p')).to.equal('PM')
expect(t(then, '%p')).to.equal('AM')
})
it('should format %P as lower cased am/pm', function () {
expect(t(now, '%P')).to.equal('pm')
expect(t(then, '%P')).to.equal('am')
})
it('should format %q as date suffix', function () {
var st = new Date('2016-03-01T03:05:03.000Z')
var nd = new Date('2016-03-02T03:05:03.000Z')
var rd = new Date('2016-03-03T03:05:03.000Z')
expect(t(st, '%q')).to.equal('st')
expect(t(nd, '%q')).to.equal('nd')
expect(t(rd, '%q')).to.equal('rd')
expect(t(now, '%q')).to.equal('th')
})
it('should format %s as UNIX seconds', function () {
expect(t(now, '%s')).to.be.match(/\d+/)
})
it('should format %u as day of week(1-7)', function () {
expect(t(now, '%u')).to.be.equal('1')
expect(t(then, '%u')).to.be.equal('7')
})
it('should format %U as week of year, starts with 0', function () {
expect(t(now, '%U')).to.equal('01')
})
it('should format %w as day of month(0-7)', function () {
expect(t(now, '%w')).to.be.equal('1')
expect(t(then, '%w')).to.be.equal('0')
})
it('should format %W as week of year, starts with 1', function () {
expect(t(now, '%W')).to.be.equal('01')
})
it('should format %x as local date string', function () {
expect(t(now, '%x')).to.equal(now.toLocaleDateString())
})
it('should format %X as local time string', function () {
expect(t(now, '%X')).to.equal(now.toLocaleTimeString())
})
it('should format %y as 2-digit year', function () {
expect(t(now, '%y')).to.equal('16')
})
it('should format %z as time zone', function () {
expect(t(now, '%z')).to.equal('+0800')
})
it('should format %z as negative time zone', function () {
var date = new Date('2016-01-04T13:15:23.000Z')
date.getTimezoneOffset = () => 480
expect(t(date, '%z')).to.equal('-0800')
})
it('should escape %% as %', function () {
expect(t(now, '%%')).to.equal('%')
})
it('should retain un-recognized formaters', function () {
expect(t(now, '%o')).to.equal('%o')
})
})
function mockUTC () {
var p = Date.prototype
function mockUTC() {
var p = Date.prototype;
p._getHours = p.getHours
p.getHours = p.getUTCHours
p._getHours = p.getHours;
p.getHours = p.getUTCHours;
p._getDays = p.getDays
p.getDays = p.getUTCDays
p._getDays = p.getDays;
p.getDays = p.getUTCDays;
p._getTimezoneOffset = p._getTimezoneOffset;
p.getTimezoneOffset = () => -480;
p._getTimezoneOffset = p._getTimezoneOffset
p.getTimezoneOffset = () => -480
}
function restoreUTC() {
var p = Date.prototype;
p.getHours = p._getHours;
p.getDays = p._getDays;
p.getTimezoneOffset = p._getTimezoneOffset;
function restoreUTC () {
var p = Date.prototype
p.getHours = p._getHours
p.getDays = p._getDays
p.getTimezoneOffset = p._getTimezoneOffset
}
+126 -126
View File
@@ -1,128 +1,128 @@
const chai = require("chai");
const sinon = require('sinon');
const expect = chai.expect;
const Errors = require('../../src/util/error.js');
chai.use(require("sinon-chai"));
const chai = require('chai')
const sinon = require('sinon')
const expect = chai.expect
const Errors = require('../../src/util/error.js')
chai.use(require('sinon-chai'))
var _ = require('../../src/util/underscore.js');
var _ = require('../../src/util/underscore.js')
describe('util/underscore', function() {
describe('.isError()', function() {
it('should return true for new Error', function() {
expect(_.isError(new Error())).to.be.true;
});
it('should return true for RenderError', function() {
var tpl = {
token: {
input: 'xx'
}
};
expect(_.isError(new Errors.RenderError(new Error(), tpl))).to.be.true;
});
it('should return true for RenderBreakError', function() {
expect(_.isError(new Errors.RenderBreakError())).to.be.true;
});
});
describe('.isString()', function() {
it('should return true for literal string', function() {
expect(_.isString('foo')).to.be.true;
});
it('should return true String instance', function() {
expect(_.isString(String('foo'))).to.be.true;
});
it('should return false for 123 ', function() {
expect(_.isString(123)).to.be.false;
});
});
describe('.forOwn()', function() {
it('should iterate all properties', function() {
var spy = sinon.spy();
var obj = {
foo: "bar"
};
_.forOwn(obj, spy);
expect(spy).to.have.been.calledWith('bar', 'foo', obj);
});
it('should not iterate over properties on prototype', function() {
var spy = sinon.spy();
var obj = Object.create({
bar: 'foo'
});
obj.foo = 'bar';
_.forOwn(obj, spy);
expect(spy).to.have.been.calledOnce;
expect(spy).to.have.been.calledWith('bar', 'foo', obj);
});
it('should break when returned false', function() {
var spy = sinon.stub().returns(false);
_.forOwn({
'foo': 'foo',
'bar': 'foo'
}, spy);
expect(spy).to.have.been.calledOnce;
});
});
describe('.isArray()', function() {
it('should return true for []', function() {
expect(_.isArray([])).to.be.true;
});
it('should return false for "foo"', function() {
expect(_.isArray("foo")).to.be.false;
});
});
describe('.echo()', function() {
it('should be transparent', function() {
expect(_.echo('foo')('bar')).to.equal('bar');
});
it('should log the arguments', function() {
var log = sinon.spy(console, 'log');
_.echo('foo')('bar');
expect(log).to.have.been.calledWith('[foo]', 'bar');
});
});
describe('.assign()', function() {
it('should handle null dst', function() {
expect(_.assign(null, {
foo: 'bar'
})).to.deep.equal({
foo: 'bar'
});
});
it('should assign 2 objects', function() {
var src = {
foo: 'foo',
bar: 'bar'
};
var dst = {
foo: 'bar',
kaa: 'kaa'
};
expect(_.assign(dst, src)).to.deep.equal({
foo: 'foo',
bar: 'bar',
kaa: 'kaa'
});
});
it('should assign 3 objects', function() {
expect(_.assign({
foo: 'foo'
}, {
bar: 'bar'
}, {
car: 'car'
})).to.deep.equal({
foo: 'foo',
bar: 'bar',
car: 'car'
});
});
});
describe('.uniq()', function() {
it('should handle empty array', function() {
expect(_.uniq([])).to.deep.equal([]);
});
it('should do uniq', function() {
expect(_.uniq([1, 'a', 'a', 1])).to.deep.equal([1, 'a']);
});
});
});
describe('util/underscore', function () {
describe('.isError()', function () {
it('should return true for new Error', function () {
expect(_.isError(new Error())).to.be.true
})
it('should return true for RenderError', function () {
var tpl = {
token: {
input: 'xx'
}
}
expect(_.isError(new Errors.RenderError(new Error(), tpl))).to.be.true
})
it('should return true for RenderBreakError', function () {
expect(_.isError(new Errors.RenderBreakError())).to.be.true
})
})
describe('.isString()', function () {
it('should return true for literal string', function () {
expect(_.isString('foo')).to.be.true
})
it('should return true String instance', function () {
expect(_.isString(String('foo'))).to.be.true
})
it('should return false for 123 ', function () {
expect(_.isString(123)).to.be.false
})
})
describe('.forOwn()', function () {
it('should iterate all properties', function () {
var spy = sinon.spy()
var obj = {
foo: 'bar'
}
_.forOwn(obj, spy)
expect(spy).to.have.been.calledWith('bar', 'foo', obj)
})
it('should not iterate over properties on prototype', function () {
var spy = sinon.spy()
var obj = Object.create({
bar: 'foo'
})
obj.foo = 'bar'
_.forOwn(obj, spy)
expect(spy).to.have.been.calledOnce
expect(spy).to.have.been.calledWith('bar', 'foo', obj)
})
it('should break when returned false', function () {
var spy = sinon.stub().returns(false)
_.forOwn({
'foo': 'foo',
'bar': 'foo'
}, spy)
expect(spy).to.have.been.calledOnce
})
})
describe('.echo()', function () {
it('should be transparent', function () {
expect(_.echo('foo')('bar')).to.equal('bar')
})
it('should log the arguments', function () {
var log = sinon.spy(console, 'log')
_.echo('foo')('bar')
expect(log).to.have.been.calledWith('[foo]', 'bar')
})
})
describe('.range()', function () {
it('should return a range of integers', function () {
expect(_.range(3, 5)).to.deep.equal([3, 4])
})
it('should treat start as 0 if omitted', function () {
expect(_.range(3)).to.deep.equal([0, 1, 2])
})
})
describe('.assign()', function () {
it('should handle null dst', function () {
expect(_.assign(null, {
foo: 'bar'
})).to.deep.equal({
foo: 'bar'
})
})
it('should assign 2 objects', function () {
var src = {
foo: 'foo',
bar: 'bar'
}
var dst = {
foo: 'bar',
kaa: 'kaa'
}
expect(_.assign(dst, src)).to.deep.equal({
foo: 'foo',
bar: 'bar',
kaa: 'kaa'
})
})
it('should assign 3 objects', function () {
expect(_.assign({
foo: 'foo'
}, {
bar: 'bar'
}, {
car: 'car'
})).to.deep.equal({
foo: 'foo',
bar: 'bar',
car: 'car'
})
})
})
describe('.uniq()', function () {
it('should handle empty array', function () {
expect(_.uniq([])).to.deep.equal([])
})
it('should do uniq', function () {
expect(_.uniq([1, 'a', 'a', 1])).to.deep.equal([1, 'a'])
})
})
})