Compare commits

...
34 Commits
Author SHA1 Message Date
harttle d36ec17621 2.0.0 2017-10-30 02:23:36 +08:00
harttle 485424cc89 feature: concat filter 2017-10-30 02:22:56 +08:00
harttle a239389044 docs for #41 2017-10-30 02:07:07 +08:00
harttle e8fa8d32f5 feature: separate options for value/tag trimming, working on #17 2017-10-30 01:46:31 +08:00
harttle 502426f621 mv whiteSpaceCtrl to a separate file 2017-10-30 00:36:21 +08:00
harttle 8c77fc5a3d fix: whiteSpace Ctrl with compliance to shopify/liquid, working on #17 2017-10-30 00:09:29 +08:00
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
64 changed files with 2728 additions and 2005 deletions
+1
View File
@@ -38,3 +38,4 @@ jspm_packages
# vim
.*.swp
package-lock.json
+4 -2
View File
@@ -1,7 +1,9 @@
language: node_js
node_js:
- "5"
- "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
+32 -27
View File
@@ -1,34 +1,35 @@
# shopify-liquid
# liquidjs
[![npm](https://img.shields.io/npm/v/shopify-liquid.svg)](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)
[![Coveralls](https://img.shields.io/coveralls/harttle/shopify-liquid.svg)](https://coveralls.io/github/harttle/shopify-liquid?branch=master)
[![GitHub issues](https://img.shields.io/github/issues-closed/harttle/shopify-liquid.svg)](https://github.com/harttle/shopify-liquid/issues)
[![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 Liquid template engine with a wide range of tags and filters,
for both Node.js and browsers.
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:
* A wide range of [filters](https://github.com/harttle/shopify-liquid/wiki/Builtin-Filters) and [tags](https://github.com/harttle/shopify-liquid/wiki/Builtin-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/shopify-liquid/wiki/Builtin-Tags>
* Builtin Filters: <https://github.com/harttle/shopify-liquid/wiki/Builtin-Filters>
* Operators: <https://github.com/harttle/shopify-liquid/wiki/Operators>
* Whitespace Control: <https://github.com/harttle/shopify-liquid/wiki/Whitespace-Control>
* 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
@@ -36,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'})
@@ -81,7 +82,7 @@ The full list of options for `Liquid()` is listed as following:
If an array, the files are looked up in the order they occur in the array.
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. Set to `""` if you do **NOT** want liquidjs to append default extname. Defaults to `".liquid"`.
* `cache` indicates whether or not to cache resolved templates. Defaults to `false`.
@@ -91,11 +92,15 @@ Defaults to `["."]`
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_tag_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.
* `trim_tag_left` is similiar to `trim_tag_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`.
* `trim_value_right` is used to strip blank characters (including ` `, `\t`, and `\r`) from the right of values (`{{ }}`) until `\n` (inclusive). Defaults to `false`.
* `trim_value_left` is similiar to `trim_value_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 consecutive blank characters including `\n` will be trimed regardless of line breaks. Defaults to `true`.
## Use with Express.js
@@ -126,11 +131,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>
@@ -194,7 +199,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
@@ -211,7 +216,7 @@ 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
@@ -221,11 +226,11 @@ engine.registerTag('upper', {
[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/shopify-liquid/wiki/Whitespace-Control
[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"
}
+721 -693
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
+108 -108
View File
@@ -1,128 +1,128 @@
const strftime = require('./src/util/strftime.js');
const _ = require('./src/util/underscore.js');
const isTruthy = require('./src/syntax.js').isTruthy;
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 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,
'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),
'concat': (v, arg) => Array.prototype.concat.call(v, arg),
'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) => 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 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
+14 -15
View File
@@ -46,12 +46,6 @@ var _engine = {
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)
@@ -59,8 +53,12 @@ var _engine = {
.then(templates => this.render(templates, ctx, opts))
},
evalOutput: function (str, scope) {
var tpl = this.parser.parseOutput(str.trim())
return this.renderer.evalOutput(tpl, scope)
console.warn('[liquidjs:deprecated] use .evalValue() instead of .evalOutput')
return this.evalValue(str, scope)
},
evalValue: function (str, scope) {
var tpl = this.parser.parseValue(str.trim())
return this.renderer.evalValue(tpl, scope)
},
registerFilter: function (name, filter) {
return this.filter.register(name, filter)
@@ -74,9 +72,7 @@ var _engine = {
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}`
}
e.message = `${e.code}: Failed to lookup ${filepath} in: ${root}`
throw e
})
},
@@ -93,8 +89,8 @@ var _engine = {
return Promise.resolve(tpl)
}
return readFileAsync(filepath)
.then(str => this.parse(str))
.then(tpl => (this.cache[filepath] = tpl))
.then(str => this.parse(str))
.then(tpl => (this.cache[filepath] = tpl))
} else {
return readFileAsync(filepath).then(str => this.parse(str, filepath))
}
@@ -119,8 +115,11 @@ function factory (options) {
root: ['.'],
cache: false,
extname: '.liquid',
trim_right: false,
trim_left: false,
trim_tag_right: false,
trim_tag_left: false,
trim_value_right: false,
trim_value_left: false,
greedy: true,
strict_filters: false,
strict_variables: false
}, options)
+29 -27
View File
@@ -1,19 +1,21 @@
{
"name": "shopify-liquid",
"version": "1.9.0",
"description": "A feature-rich Liquid template engine for Node.js and browsers, with compliance with the Ruby version.",
"name": "liquidjs",
"version": "2.0.0",
"description": "A Liquid template engine for Node.js and browsers, with all shopify/liquid features.",
"main": "index.js",
"scripts": {
"lint": "eslint src/ test/",
"test": "npm run lint && mocha --recursive",
"test": "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",
"preversion": "npm run lint && 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",
@@ -25,33 +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": "^6.0.0",
"coveralls": "^2.11.9",
"eslint": "^3.19.0",
"eslint-config-standard": "^10.2.0",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-mocha": "^4.9.0",
"eslint-plugin-node": "^4.2.2",
"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.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"
"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"
}
}
+1
View File
@@ -82,6 +82,7 @@ function parseLiteral (str) {
if (res) {
return str.slice(1, -1)
}
throw new TypeError(`cannot parse '${str}' as literal`)
}
module.exports = {
+6 -6
View File
@@ -55,8 +55,8 @@ module.exports = function (Tag, Filter) {
var tpl = null
if (token.type === 'tag') {
tpl = parseTag(token, tokens)
} else if (token.type === 'output') {
tpl = parseOutput(token.value)
} else if (token.type === 'value') {
tpl = parseValue(token.value)
} else { // token.type === 'html'
tpl = token
}
@@ -72,9 +72,9 @@ module.exports = function (Tag, Filter) {
return Tag.construct(token, tokens)
}
function parseOutput (str) {
function parseValue (str) {
var match = lexical.matchValue(str)
assert(match, `illegal output string: ${str}`)
assert(match, `illegal value string: ${str}`)
var initial = match[0]
str = str.substr(match.index + match[0].length)
@@ -85,7 +85,7 @@ module.exports = function (Tag, Filter) {
}
return {
type: 'output',
type: 'value',
initial: initial,
filters: filters.map(str => Filter.construct(str))
}
@@ -100,6 +100,6 @@ module.exports = function (Tag, Filter) {
parse,
parseTag,
parseStream,
parseOutput
parseValue
}
}
+4 -4
View File
@@ -27,9 +27,9 @@ var render = {
if (template.type === 'tag') {
return this.renderTag(template, scope)
.then(partial => partial === undefined ? '' : partial)
} else if (template.type === 'output') {
} else if (template.type === 'value') {
return Promise.resolve()
.then(() => this.evalOutput(template, scope))
.then(() => this.evalValue(template, scope))
.then(partial => partial === undefined ? '' : stringify(partial))
} else { // template.type === 'html'
return Promise.resolve(template.value)
@@ -47,8 +47,8 @@ var render = {
return template.render(scope)
},
evalOutput: function (template, scope) {
assert(scope, 'unable to evalOutput: scope undefined')
evalValue: function (template, scope) {
assert(scope, 'unable to evalValue: scope undefined')
return template.filters.reduce(
(prev, filter) => filter.render(prev, scope),
Syntax.evalExp(template.initial, scope))
+96 -88
View File
@@ -1,7 +1,6 @@
const _ = require('./util/underscore.js')
const lexical = require('./lexical.js')
const assert = require('./util/assert.js')
const toStr = Object.prototype.toString
var Scope = {
getAll: function () {
@@ -12,32 +11,17 @@ var Scope = {
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
}
try {
return this.getPropertyByPath(this.scopes, str)
} catch (e) {
if (!/undefined variable/.test(e.message) || this.opts.strict_variables) {
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)
var scope = this.findScopeFor(k)
setPropertyByPath(scope, k, v)
return this
},
push: function (ctx) {
@@ -47,6 +31,16 @@ var Scope = {
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)
@@ -54,39 +48,23 @@ var Scope = {
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) {
getPropertyByPath: function (scopes, path) {
var paths = this.propertyAccessSeq(path + '')
var varName = paths.shift()
if (!obj.hasOwnProperty(varName)) {
throw new TypeError('undefined variable')
if (!paths.length) {
throw new TypeError('undefined variable: ' + path)
}
var variable = obj[varName]
var lastName = paths.pop()
paths.forEach(p => (variable = variable[p]))
if (undefined !== lastName) {
if (lastName === 'size' &&
(toStr.call(variable) === '[object Array]' ||
toStr.call(variable) === '[object String]')) {
return variable.length
}
variable = variable[lastName]
}
return variable
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
)
},
/*
@@ -100,49 +78,79 @@ var Scope = {
propertyAccessSeq: function (str) {
var seq = []
var name = ''
for (var i = 0; i < str.length; i++) {
if (str[i] === '[') {
seq.push(name)
name = ''
var j
var i = 0
while (i < str.length) {
switch (str[i]) {
case '[':
push()
var delemiter = str[i + 1]
if (delemiter !== "'" && delemiter !== '"') {
// foo[bar.coo]
var j = matchRightBracket(str, i + 1)
assert(j !== -1, `unbalanced []: ${str}`)
name = str.slice(i + 1, j)
if (lexical.isInteger(name)) {
// foo[1]
seq.push(name)
} else {
// foo["bar"]
seq.push(this.get(name))
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
}
name = ''
i = j
} else {
// foo["bar"]
j = str.indexOf(delemiter, i + 2)
assert(j !== -1, `unbalanced ${delemiter}: ${str}`)
name = str.slice(i + 2, j)
seq.push(name)
name = ''
i = j + 2
}
} else if (str[i] === '.') {
// foo.bar
seq.push(name)
name = ''
} else {
// foo.bar
name += str[i]
break
case '.':// foo.bar, foo[0].bar
push()
i++
break
default:// foo.bar
name += str[i]
i++
}
}
if (name.length) seq.push(name)
push()
return seq
function push () {
if (name.length) seq.push(name)
name = ''
}
}
}
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] || {}
}
}
function getValueFromParent (key, value) {
return (key === 'size' && (_.isArray(value) || _.isString(value)))
? value.length
: value[key]
}
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++) {
+1
View File
@@ -40,6 +40,7 @@ function evalValue (str, scope) {
if (lexical.isVariable(str)) {
return scope.get(str)
}
throw new TypeError(`cannot eval '${str}' as value`)
}
function isTruthy (val) {
+1 -11
View File
@@ -1,5 +1,4 @@
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')
@@ -26,16 +25,7 @@ module.exports = function () {
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)
})
return Promise.resolve().then(() => impl.render(scope, obj))
},
parse: function (token, tokens) {
this.type = 'tag'
+67 -68
View File
@@ -1,91 +1,90 @@
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 whiteSpaceCtrl = require('./whitespace-ctrl.js')
const assert = require('./util/assert.js')
function parse (html, filepath, options) {
assert(_.isString(html), 'illegal input type')
function parse (input, file, options) {
assert(_.isString(input), 'illegal input')
html = whiteSpaceCtrl(html, options)
var tokens = []
var syntax = /({%-?([\s\S]*?)-?%})|({{([\s\S]*?)}})/g
var result, htmlFragment, token
var rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
var currIndent = 0
var lineNumber = LineNumber(input)
var lastMatchEnd = 0
var lastMatchBegin = -1
var parsedLinesCount = 0
var tokens = []
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
})
for (var match; (match = rLiquid.exec(input)); lastMatchEnd = rLiquid.lastIndex) {
if (match.index > lastMatchEnd) {
tokens.push(parseHTMLToken(lastMatchEnd, match.index))
}
if (result[1]) {
// tag appeared
token = factory('tag', 1, result)
tokens.push(match[1]
? parseTagToken(match[1], match[2].trim(), match.index)
: parseValueToken(match[3], match[4].trim(), match.index))
}
if (input.length > lastMatchEnd) {
tokens.push(parseHTMLToken(lastMatchEnd, input.length))
}
whiteSpaceCtrl(tokens, options)
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]
tokens.push(token)
} else {
// output
token = factory('output', 3, result)
tokens.push(token)
function parseTagToken (raw, value, pos) {
var match = value.match(lexical.tagLine)
var token = {
type: 'tag',
indent: currIndent,
line: lineNumber.get(pos),
trim_left: raw.slice(0, 3) === '{%-',
trim_right: raw.slice(-3) === '-%}',
raw,
value,
input,
file
}
lastMatchEnd = syntax.lastIndex
if (!match) {
throw new TokenizationError(`illegal tag syntax`, token)
}
token.name = match[1]
token.args = match[2]
return token
}
// remaining html
if (html.length > lastMatchEnd) {
htmlFragment = html.slice(lastMatchEnd, html.length)
tokens.push({
function parseValueToken (raw, value, pos) {
return {
type: 'value',
line: lineNumber.get(pos),
trim_left: raw.slice(0, 3) === '{{-',
trim_right: raw.slice(-3) === '-}}',
raw,
value,
input,
file
}
}
function parseHTMLToken (begin, end) {
var htmlFragment = input.slice(begin, end)
currIndent = _.last((htmlFragment || '').split('\n')).length
return {
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
}
}
function whiteSpaceCtrl (html, options) {
options = options || {}
if (options.trim_left) {
html = html.replace(/{%-?/g, '{%-')
function LineNumber (html) {
var parsedLinesCount = 0
var lastMatchBegin = -1
return {
get: function (pos) {
var lines = html.slice(lastMatchBegin + 1, pos).split('\n')
parsedLinesCount += lines.length - 1
lastMatchBegin = pos
return parsedLinesCount + 1
}
}
if (options.trim_right) {
html = html.replace(/-?%}/g, '-%}')
}
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
-3
View File
@@ -2,9 +2,6 @@ const AssertionError = require('./error.js').AssertionError
function assert (predicate, message) {
if (!predicate) {
if (message instanceof Error) {
throw message
}
message = message || `expect ${predicate} to be true`
throw new AssertionError(message)
}
+26 -38
View File
@@ -1,10 +1,14 @@
const _ = require('./underscore.js')
function TokenizationError (message, token) {
function initError () {
this.name = this.constructor.name
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor)
}
this.name = this.constructor.name
}
function initLiquidError (message, token) {
initError.call(this)
this.input = token.input
this.line = token.line
@@ -12,7 +16,11 @@ function TokenizationError (message, token) {
var context = mkContext(token.input, token.line)
this.message = mkMessage(message, token)
this.stack = context + '\n' + (this.stack || '')
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
@@ -20,55 +28,35 @@ TokenizationError.prototype.constructor = TokenizationError
function ParseError (e, token) {
_.assign(this, e)
this.originalError = e
this.name = this.constructor.name
this.input = token.input
this.line = token.line
this.file = token.file
var context = mkContext(token.input, token.line)
this.message = mkMessage(e.message || 'Unkown Error', token)
this.stack = context + '\n' + (e.stack || '')
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
// return the original render error
if (e instanceof RenderError) {
return e
}
_.assign(this, e)
this.originalError = e
this.name = this.constructor.name
this.input = tpl.token.input
this.line = tpl.token.line
this.file = tpl.token.file
var context = mkContext(tpl.token.input, tpl.token.line)
this.message = mkMessage(e.message || 'Unkown Error', tpl.token)
this.stack = context + '\n' + (e.stack || '')
initLiquidError.call(this, e.message, tpl.token)
}
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 || ''
initError.call(this)
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
initError.call(this)
this.message = message + ''
}
AssertionError.prototype = Object.create(Error.prototype)
AssertionError.prototype.constructor = AssertionError
@@ -79,14 +67,14 @@ function mkContext (input, line) {
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')
.range(begin, end + 1)
.map(l => [
(l === line) ? '>> ' : ' ',
align(l, end),
'| ',
lines[l - 1]
].join(''))
.join('\n')
return context
}
+2 -2
View File
@@ -25,8 +25,8 @@ function mapSeries (iterable, iteratee) {
var result = []
iterable.forEach(function (item, idx) {
ret = ret
.then(() => iteratee(item, idx, iterable))
.then(x => result.push(x))
.then(() => iteratee(item, idx, iterable))
.then(x => result.push(x))
})
return ret.then(() => result)
}
+1
View File
@@ -163,6 +163,7 @@ var formatCodes = {
},
z: function (d) {
var tz = d.getTimezoneOffset() / 60 * 100
console.log('tz', tz)
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4)
},
'%': function () {
+20 -9
View File
@@ -1,3 +1,5 @@
const toStr = Object.prototype.toString
/*
* Checks if value is classified as a String primitive or object.
* @param {any} value The value to check.
@@ -7,9 +9,18 @@ function isString (value) {
return value instanceof String || typeof value === '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]
// [object XXXError]
return signature.substr(-6, 5) === 'Error' ||
(typeof value.message === 'string' && typeof value.name === 'string')
}
@@ -53,18 +64,14 @@ function assign (object) {
}
function _assignBinary (dst, src) {
if (!dst) return dst
forOwn(src, function (v, k) {
dst[k] = v
})
return dst
}
function echo (prefix) {
return v => {
console.log('[' + prefix + ']', v)
return v
}
function last (arr) {
return arr[arr.length - 1]
}
function uniq (arr) {
@@ -113,14 +120,18 @@ function range (start, stop, step) {
return arr
}
// lang
exports.isString = isString
exports.isObject = isObject
exports.isArray = isArray
exports.isNil = isNil
exports.isError = isError
// array
exports.range = range
exports.last = last
// object
exports.forOwn = forOwn
exports.assign = assign
exports.uniq = uniq
exports.echo = echo
+48
View File
@@ -0,0 +1,48 @@
const _ = require('./util/underscore.js')
function whiteSpaceCtrl (tokens, options) {
options = _.assign({ greedy: true }, options)
var inRaw = false
tokens.forEach((token, i) => {
if (shouldTrimLeft(token, inRaw, options)) {
trimLeft(tokens[i - 1], options.greedy)
}
if (token.type === 'tag' && token.name === 'raw') inRaw = true
if (token.type === 'tag' && token.name === 'endraw') inRaw = false
if (shouldTrimRight(token, inRaw, options)) {
trimRight(tokens[i + 1], options.greedy)
}
})
}
function shouldTrimLeft (token, inRaw, options) {
if (inRaw) return false
if (token.type === 'tag') return token.trim_left || options.trim_tag_left
if (token.type === 'value') return token.trim_left || options.trim_value_left
}
function shouldTrimRight (token, inRaw, options) {
if (inRaw) return false
if (token.type === 'tag') return token.trim_right || options.trim_tag_right
if (token.type === 'value') return token.trim_right || options.trim_value_right
}
function trimLeft (token, greedy) {
if (!token || token.type !== 'html') return
console.log('trimming', token.value)
var rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
token.value = token.value.replace(rLeft, '')
}
function trimRight (token, greedy) {
if (!token || token.type !== 'html') return
var rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
token.value = token.value.replace(rRight, '')
}
module.exports = whiteSpaceCtrl
+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.evalValue(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)
}
})
}
+4 -4
View File
@@ -43,7 +43,7 @@ module.exports = function (liquid) {
if (_.isString(collection) && collection.length > 0) {
collection = [collection]
} else if (_.isObject(collection)) {
collection = Object.keys(collection)
collection = Object.keys(collection).map((key) => [key, collection[key]])
}
}
if (!Array.isArray(collection) || !collection.length) {
@@ -74,9 +74,9 @@ module.exports = function (liquid) {
var html = ''
return mapSeries(contexts, (context) => {
scope.push(context)
return liquid.renderer
.renderTemplates(this.templates, scope)
return Promise.resolve()
.then(() => scope.push(context))
.then(() => liquid.renderer.renderTemplates(this.templates, scope))
.then(partial => (html += partial))
.catch(e => {
if (e instanceof RenderBreakError) {
+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
})
}
})
}
+16 -16
View File
@@ -1,16 +1,16 @@
module.exports = function(engine){
require("./assign.js")(engine);
require("./capture.js")(engine);
require("./case.js")(engine);
require("./comment.js")(engine);
require("./cycle.js")(engine);
require("./decrement.js")(engine);
require("./for.js")(engine);
require("./if.js")(engine);
require("./include.js")(engine);
require("./increment.js")(engine);
require("./layout.js")(engine);
require("./raw.js")(engine);
require("./tablerow.js")(engine);
require("./unless.js")(engine);
};
module.exports = function (engine) {
require('./assign.js')(engine)
require('./capture.js')(engine)
require('./case.js')(engine)
require('./comment.js')(engine)
require('./cycle.js')(engine)
require('./decrement.js')(engine)
require('./for.js')(engine)
require('./if.js')(engine)
require('./include.js')(engine)
require('./increment.js')(engine)
require('./layout.js')(engine)
require('./raw.js')(engine)
require('./tablerow.js')(engine)
require('./unless.js')(engine)
}
+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)
}
}
})
}
+7 -7
View File
@@ -7,13 +7,13 @@ module.exports = function (liquid) {
var stream = liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
if (token.name === 'endraw') stream.stop()
else this.tokens.push(token)
})
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
.on('token', 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) {
+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
})
}
})
}
+10 -10
View File
@@ -32,8 +32,8 @@ describe('engine#express()', function () {
mock({ '/views/name.html': 'My name is {{name}}.' })
app.set('views', ['/views'])
request(app).get('/name')
.expect('My name is harttle.')
.expect(200, done)
.expect('My name is harttle.')
.expect(200, done)
})
it('should pass error when file not found', function (done) {
var view = {
@@ -58,8 +58,8 @@ describe('engine#express()', function () {
})
app.set('views', ['/views'])
request(app).get('/include/foo')
.expect('foo')
.expect(200, done)
.expect('foo')
.expect(200, done)
})
it('should respect express views (Array) when lookup', function (done) {
mock({
@@ -68,8 +68,8 @@ describe('engine#express()', function () {
})
app.set('views', ['/views', '/partials'])
request(app).get('/include/bar')
.expect('bar')
.expect(200, done)
.expect('bar')
.expect(200, done)
})
it('should respect express views (String) when lookup', function (done) {
mock({
@@ -78,8 +78,8 @@ describe('engine#express()', function () {
})
app.set('views', '/views')
request(app).get('/include/bar')
.expect('bar')
.expect(200, done)
.expect('bar')
.expect(200, done)
})
it('should respect express views (Undefined) when lookup', function (done) {
var files = {}
@@ -88,7 +88,7 @@ describe('engine#express()', function () {
mock(files)
request(app).get('/include/bar')
.expect('bar')
.expect(200, done)
.expect('bar')
.expect(200, done)
})
})
+89 -41
View File
@@ -32,7 +32,7 @@ describe('filters', function () {
describe('append', function () {
it('should return "-3abc" for -3, "abc"',
() => test('{{ -3 | append: "abc" }}', '-3abc'))
() => test('{{ -3 | append: "abc" }}', '-3abc'))
it('should return "abar" for "a",foo', () => test('{{ "a" | append: foo }}', 'abar'))
})
@@ -45,6 +45,44 @@ describe('filters', function () {
it('should return "184" for 183.357', () => test('{{ 183.357 | ceil }}', '184'))
})
describe('concat', function () {
it('should concat arrays', () => test(`
{%- assign fruits = "apples, oranges, peaches" | split: ", " -%}
{%- assign vegetables = "carrots, turnips, potatoes" | split: ", " -%}
{%- assign everything = fruits | concat: vegetables -%}
{%- for item in everything -%}
- {{ item }}
{% endfor -%}`,
`- apples
- oranges
- peaches
- carrots
- turnips
- potatoes
`))
it('should support chained concat', () => test(`
{%- assign fruits = "apples, oranges, peaches" | split: ", " -%}
{%- assign vegetables = "carrots, turnips, potatoes" | split: ", " -%}
{%- assign furniture = "chairs, tables, shelves" | split: ", " -%}
{%- assign everything = fruits | concat: vegetables | concat: furniture -%}
{%- for item in everything -%}
- {{ item }}
{% endfor -%}`,
`- apples
- oranges
- peaches
- carrots
- turnips
- potatoes
- chairs
- tables
- shelves
`))
})
describe('date', function () {
it('should support date: %a %b %d %Y', function () {
var str = ctx.date.toDateString()
@@ -72,15 +110,15 @@ describe('filters', function () {
describe('downcase', function () {
it('should return "parker moore" for "Parker Moore"',
() => test('{{ "Parker Moore" | downcase }}', 'parker moore'))
() => test('{{ "Parker Moore" | downcase }}', 'parker moore'))
it('should return "apple" for "apple"',
() => test('{{ "apple" | downcase }}', '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;?')
'Have you read &#39;James &amp; the Giant Peach&#39;?')
})
it('should escape normal string', function () {
return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara')
@@ -92,9 +130,9 @@ describe('filters', function () {
describe('escape_once', function () {
it('should do escape', () =>
test('{{ "1 < 2 & 3" | escape_once }}', '1 &lt; 2 &amp; 3'))
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'))
() => test('{{ "1 &lt; 2 &amp; 3" | escape_once }}', '1 &lt; 2 &amp; 3'))
})
it('should support split/first', function () {
@@ -135,7 +173,7 @@ describe('filters', 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'))
() => 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'))
})
@@ -144,7 +182,7 @@ describe('filters', 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'))
() => test('{{ 183.357 | modulo: 12 }}', '3.357'))
it('should convert string', () => test('{{ "24" | modulo: "7" }}', '3'))
})
@@ -164,7 +202,7 @@ describe('filters', 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'))
() => 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'))
})
@@ -172,60 +210,60 @@ describe('filters', function () {
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 ')
'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')
'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')
'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' +
'{{ 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')
'.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'))
() => 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!')
' So much room for activities!')
})
describe('size', function () {
it('should return string length',
() => test('{{ "Ground control to Major Tom." | size }}', '28'))
() => 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'))
() => 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'))
() => test('{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}{{ my_array.size }}', '4'))
})
describe('slice', function () {
@@ -239,7 +277,7 @@ describe('filters', 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 () {
@@ -247,18 +285,18 @@ describe('filters', function () {
'{% 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!')
'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?')
'Have you read Ulysses?')
})
it('should strip until empty', function () {
return test('{{"<br/><br />< p ></p></ p >" | strip_html }}', '')
@@ -269,71 +307,81 @@ describe('filters', 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'))
() => 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...')
'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.')
'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')
'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')
'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...')
'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.')
'Ground control to Major Tom.')
})
it('should truncate with custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "--" }}',
'Ground control to--')
'Ground control to--')
})
it('should truncate with empty custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "" }}',
'Ground control to')
'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'))
describe('url_encode', function () {
it('should encode @',
() => test('{{ "[email protected]" | url_encode }}', 'john%40liquid.com'))
() => test('{{ "[email protected]" | url_encode }}', 'john%40liquid.com'))
it('should encode <space>',
() => test('{{ "Tetsuro Takara" | url_encode }}', 'Tetsuro%20Takara'))
() => test('{{ "Tetsuro Takara" | url_encode }}', 'Tetsuro%20Takara'))
})
describe('obj_test', function () {
+20 -13
View File
@@ -86,21 +86,28 @@ describe('lexical', function () {
expect(lexical.isVariable('[0][12].bar[0]')).to.equal(false)
})
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)
})
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 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)
})
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)
})
it('should parse string literal', function () {
expect(lexical.parseLiteral('"ab\'c"')).to.equal("ab'c")
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 () {
+22 -106
View File
@@ -24,6 +24,7 @@ describe('liquid', function () {
strict_filters: true
})
mock({
'/root/files/bar': 'bar',
'/root/files/foo.html': 'foo',
'/root/files/name.html': 'My name is {{name}}.',
'/un-readable.html': mock.file({
@@ -34,14 +35,20 @@ describe('liquid', function () {
afterEach(function () {
mock.restore()
})
describe('{{output}}', function () {
it('should output object', function () {
describe('Liquid', function () {
it('should ignore invalid root option', function () {
var liquid = Liquid({ root: /regex/ })
expect(liquid.options.root).to.deep.equal([])
})
})
describe('{{value}}', function () {
it('should value object', function () {
return expect(engine.parseAndRender('{{obj}}', ctx)).to.eventually.equal('{"foo":"bar"}')
})
it('should output array', function () {
it('should value array', function () {
return expect(engine.parseAndRender('{{arr}}', ctx)).to.eventually.equal('[-2,"a"]')
})
it('should output undefined to empty', function () {
it('should value 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 () {
@@ -83,11 +90,16 @@ describe('liquid', function () {
describe('#renderFile()', function () {
it('should render file', function () {
return expect(engine.renderFile('/root/files/foo.html', ctx))
.to.eventually.equal('foo')
.to.eventually.equal('foo')
})
it('should find files without extname', function () {
var engine = Liquid({root: '/root', extname: ''})
return expect(engine.renderFile('/root/files/bar', ctx))
.to.eventually.equal('bar')
})
it('should accept relative path', function () {
return expect(engine.renderFile('files/foo.html'))
.to.eventually.equal('foo')
.to.eventually.equal('foo')
})
it('should resolve array as root', function () {
engine = Liquid({
@@ -95,7 +107,7 @@ describe('liquid', function () {
extname: '.html'
})
return expect(engine.renderFile('files/foo.html'))
.to.eventually.equal('foo')
.to.eventually.equal('foo')
})
it('should default root to cwd', function () {
var files = {}
@@ -106,7 +118,7 @@ describe('liquid', function () {
extname: '.html'
})
return expect(engine.renderFile('foo.html'))
.to.eventually.equal('FOO')
.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.')
@@ -120,107 +132,11 @@ describe('liquid', function () {
extname: '.html'
})
return expect(engine.renderFile('/not/exist.html')).to
.be.rejectedWith(/failed to lookup \/not\/exist.html in: \/boo,\/root\//i)
.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)
.be.rejectedWith(/EACCES/)
})
})
})
+42
View File
@@ -0,0 +1,42 @@
const chai = require('chai')
const expect = chai.expect
const mock = require('mock-fs')
const Liquid = require('../..')
chai.use(require('chai-as-promised'))
describe('cache options', function () {
var engine
beforeEach(function () {
engine = Liquid({
root: '/root/',
extname: '.html'
})
mock({ '/root/files/foo.html': 'foo' })
})
afterEach(function () {
mock.restore()
})
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'))
})
})
+35
View File
@@ -0,0 +1,35 @@
const chai = require('chai')
const expect = chai.expect
const Liquid = require('../..')
chai.use(require('chai-as-promised'))
describe('strict options', function () {
var engine
var ctx = {}
beforeEach(function () {
engine = Liquid({
root: '/root/',
extname: '.html'
})
})
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/)
})
})
+84
View File
@@ -0,0 +1,84 @@
const chai = require('chai')
const expect = chai.expect
const Liquid = require('../..')
chai.use(require('chai-as-promised'))
describe('trimming', function () {
var ctx = {name: 'harttle'}
describe('tag trimming', function () {
it('should respect trim_tag_left', function () {
var engine = Liquid({ trim_tag_left: true })
return expect(engine.parseAndRender(' \n \t{%if true%}foo{%endif%} '))
.to.eventually.equal('foo ')
})
it('should respect trim_tag_right', function () {
var engine = Liquid({ trim_tag_right: true })
return expect(engine.parseAndRender('\t{%if true%}foo{%endif%} \n'))
.to.eventually.equal('\tfoo')
})
it('should not trim value', function () {
var engine = Liquid({ trim_tag_left: true, trim_tag_right: true })
return expect(engine.parseAndRender('{%if true%}a {{name}} b{%endif%}', ctx))
.to.eventually.equal('a harttle b')
})
})
describe('value trimming', function () {
it('should respect trim_value_left', function () {
var engine = Liquid({ trim_value_left: true })
return expect(engine.parseAndRender(' \n \t{{name}} ', ctx))
.to.eventually.equal('harttle ')
})
it('should respect trim_value_right', function () {
var engine = Liquid({ trim_value_right: true })
return expect(engine.parseAndRender(' \n \t{{name}} ', ctx))
.to.eventually.equal(' \n \tharttle')
})
it('should respect not trim tag', function () {
var engine = Liquid({ trim_value_left: true, trim_value_right: true })
return expect(engine.parseAndRender('\t{% if true %} aha {%endif%}\t'))
.to.eventually.equal('\t aha \t')
})
})
describe('greedy', function () {
var src = '\n {%-if true-%}\n a \n{{-name-}}{%-endif-%}\n '
it('should enable greedy by default', function () {
var engine = Liquid()
return expect(engine.parseAndRender(src, ctx))
.to.eventually.equal('aharttle')
})
it('should respect to greedy:false by default', function () {
var engine = Liquid({greedy: false})
return expect(engine.parseAndRender(src, ctx))
.to.eventually.equal('\n a \nharttle ')
})
})
describe('markup', function () {
it('should support trim using markup', function () {
var 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 -%}'
].join('\n')
var dst = 'Wow, John G. Chalmers-Smith, you have a long name!'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
})
it('should not trim when not specified', function () {
var 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 %}'
].join('\n')
var dst = '\n\n Wow, John G. Chalmers-Smith, you have a long name!\n'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
})
})
})
+10 -10
View File
@@ -19,28 +19,28 @@ describe('template', function () {
template = Template(tag, filter)
})
it('should throw when output string illegal', function () {
it('should throw when value string illegal', function () {
expect(function () {
template.parseOutput('/')
}).to.throw(/illegal output string/)
template.parseValue('/')
}).to.throw(/illegal value string/)
})
it('should parse output string', function () {
var tpl = template.parseOutput('foo')
expect(tpl.type).to.equal('output')
it('should parse value string', function () {
var tpl = template.parseValue('foo')
expect(tpl.type).to.equal('value')
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"')
it('should parse value string with a simple filter', function () {
var tpl = template.parseValue('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')
it('should parse value string with filters', function () {
var tpl = template.parseValue('foo | add: "|" | add')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters.length).to.equal(2)
})
+7 -7
View File
@@ -44,23 +44,23 @@ describe('render', function () {
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)
var tpl = Template.parseValue('foo.bar[0] | date: "b" | time:2')
render.evalValue(tpl, scope)
expect(date).to.have.been.calledWith('a', 'b')
expect(time).to.have.been.calledWith('y', 2)
})
describe('.evalOutput()', function () {
describe('.evalValue()', function () {
it('should throw when scope undefined', function () {
expect(function () {
render.evalOutput()
render.evalValue()
}).to.throw(/scope undefined/)
})
it('should eval output', function () {
it('should eval value', 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')
var tpl = Template.parseValue('foo.bar[0] | date: "b" | time:2')
expect(render.evalValue(tpl, scope)).to.equal('ab6')
})
})
})
+37 -9
View File
@@ -20,27 +20,31 @@ describe('scope', function () {
describe('#propertyAccessSeq()', function () {
it('should handle dot syntax', function () {
expect(scope.propertyAccessSeq('foo.bar'))
.to.deep.equal(['foo', 'bar'])
.to.deep.equal(['foo', 'bar'])
})
it('should handle [<String>] syntax', function () {
expect(scope.propertyAccessSeq('foo["bar"]'))
.to.deep.equal(['foo', 'bar'])
.to.deep.equal(['foo', 'bar'])
})
it('should handle [<Identifier>] syntax', function () {
expect(scope.propertyAccessSeq('foo[foo]'))
.to.deep.equal(['foo', 'zoo'])
.to.deep.equal(['foo', 'zoo'])
})
it('should handle nested access 1', function () {
expect(scope.propertyAccessSeq('foo[bar.zoo]'))
.to.deep.equal(['foo', 'coo'])
.to.deep.equal(['foo', 'coo'])
})
it('should handle nested access 2', function () {
expect(scope.propertyAccessSeq('foo[bar["zoo"]]'))
.to.deep.equal(['foo', 'coo'])
.to.deep.equal(['foo', 'coo'])
})
it('should handle nested access 3', function () {
expect(scope.propertyAccessSeq('bar["foo"].zoo'))
.to.deep.equal(['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'])
})
})
@@ -94,7 +98,13 @@ describe('scope', function () {
expect(scope.get('bar[foo]')).to.equal('coo')
})
it('should support nested case', function () {
it('should return undefined when not exist', function () {
expect(scope.get('foo.foo.foo')).to.be.undefined
})
})
describe('#set', function () {
it('should set nested value', function () {
scope.set('posts', {
'first': {
'name': 'A Nice Day'
@@ -105,8 +115,19 @@ describe('scope', function () {
})
expect(scope.get('posts[category.diary[0]].name'), 'A Nice Day')
})
})
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 () {
@@ -114,12 +135,19 @@ describe('scope', function () {
strict_variables: true
})
})
it('should throw undefined in strict mode', function () {
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({
+16 -9
View File
@@ -20,19 +20,26 @@ describe('expression', function () {
})
})
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 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('.isTruthy()', function () {
// Spec: https://shopify.github.io/liquid/basics/truthy-and-falsy/
// 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
+20 -20
View File
@@ -43,13 +43,13 @@ describe('tag', function () {
render: spy
})
return tag
.construct({
type: 'tag',
value: 'foo',
name: 'foo'
}, [])
.render(scope, {})
.then(() => expect(spy).to.have.been.called)
.construct({
type: 'tag',
value: 'foo',
name: 'foo'
}, [])
.render(scope, {})
.then(() => expect(spy).to.have.been.called)
})
describe('hash', function () {
@@ -68,31 +68,31 @@ describe('tag', function () {
})
it('should call tag.render with scope', function () {
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch(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'
}))
.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
}))
.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
}))
.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'
}))
.then(() => expect(spy).to.have.been.calledWithMatch(scope, {
dd: 'uoo'
}))
})
})
})
+3 -3
View File
@@ -14,17 +14,17 @@ describe('tags/assign', function () {
it('should assign as string', function () {
var src = '{% assign foo="bar" %}{{foo}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('bar')
.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]')
.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')
.to.eventually.equal('A')
})
it('should assign var-1', function () {
var src = '{% assign var-1 = 5 %}{{ var-1 }}'
+3 -3
View File
@@ -9,18 +9,18 @@ describe('tags/capture', function () {
it('should support capture', function () {
var src = '{% capture f %}{{"a" | capitalize}}{%endcapture%}{{f}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('A')
.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/)
.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/)
.to.be.rejectedWith(/tag .* not closed/)
})
})
+17 -10
View File
@@ -6,19 +6,19 @@ chai.use(require('chai-as-promised'))
describe('tags/case', function () {
var liquid = Liquid()
it('should support case 1', function () {
it('should reject if not closed', function () {
var src = '{% case "foo"%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% case "foo"%} not closed/)
.to.be.rejectedWith(/{% case "foo"%} not closed/)
})
it('should support case 2', function () {
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')
.to.eventually.equal('foo')
})
it('should support case 3', function () {
it('should resolve empty string if not hit', function () {
var src = '{% case empty %}' +
'{% when "foo" %}foo{% when ""%}bar' +
'{%endcase%}'
@@ -26,20 +26,27 @@ describe('tags/case', function () {
empty: ''
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('bar')
.to.eventually.equal('bar')
})
it('should support case 4', function () {
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('')
.to.eventually.equal('')
})
it('should support case 5', function () {
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')
.to.eventually.equal('d')
})
})
+3 -3
View File
@@ -8,16 +8,16 @@ describe('tags/comment', function () {
it('should support comment 1', function () {
var src = '{% comment %}{% raw%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% comment %} not closed/)
.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.')
.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('')
.to.eventually.equal('')
})
})
+4 -4
View File
@@ -9,12 +9,12 @@ describe('tags/cycle', function () {
it('should support cycle', function () {
var src = "{% cycle '1', '2', '3' %}"
return expect(liquid.parseAndRender(src + src + src + src))
.to.eventually.equal('1231')
.to.eventually.equal('1231')
})
it('should throw when cycle candidates empty', function () {
return expect(liquid.parseAndRender('{%cycle%}'))
.to.be.rejectedWith(/empty candidates/)
.to.be.rejectedWith(/empty candidates/)
})
it('should support cycle in for block', function () {
@@ -23,7 +23,7 @@ describe('tags/cycle', function () {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1e1e1')
.to.eventually.equal('1e1e1')
})
it('should support cycle group', function () {
@@ -34,6 +34,6 @@ describe('tags/cycle', function () {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('121')
.to.eventually.equal('121')
})
})
+3 -3
View File
@@ -18,13 +18,13 @@ describe('tags/decrement', function () {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('0')
.to.eventually.equal('0')
})
it('should decrement undefined', function () {
var src = '{% decrement empty %}{{empty}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1')
.to.eventually.equal('-1')
})
it('should support decrement multiple times', function () {
@@ -33,6 +33,6 @@ describe('tags/decrement', function () {
foo: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('-1')
.to.eventually.equal('-1')
})
})
+70 -39
View File
@@ -7,6 +7,9 @@ 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
@@ -21,19 +24,40 @@ describe('tags/for', function () {
it('should support array', function () {
var src = '{%for c in alpha%}{{c}}{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('abc')
.to.eventually.equal('abc')
})
it('should support object', function () {
var src = '{%for key in obj%}{{key}}-{%else%}b{%endfor%}'
var src = '{%for item in obj%}{{item[0]}},{{item[1]}}-{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('foo-coo-')
.to.eventually.equal('foo,bar-coo,haa-')
})
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/)
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')
})
})
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 () {
@@ -43,6 +67,12 @@ describe('tags/for', function () {
.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))
@@ -80,7 +110,7 @@ describe('tags/for', function () {
'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)
.to.eventually.equal(dst)
})
it('should support for with continue', function () {
@@ -88,46 +118,47 @@ describe('tags/for', function () {
'{{i}}{% continue %}after' +
'{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12345')
.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);
// });
'{% if i == 4 %}{% break %}{% endif %}' +
'{{ i }}' +
'{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('123')
.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 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')
})
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 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')
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')
})
})
})
+23 -23
View File
@@ -12,92 +12,92 @@ describe('tags/if', function () {
emptyArray: []
}
it('should support if 1', function () {
it('should throw if not closed', function () {
var src = '{% if false%}yes'
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag {% if false%} not closed/)
.to.be.rejectedWith(/tag {% if false%} not closed/)
})
it('should support if 2', function () {
it('should treat Array truthy', function () {
var src = '{%if emptyArray%}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a')
.to.eventually.equal('a')
})
it('should support if 3', function () {
it('should support ==', function () {
var src = '{% if 2==3 %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
.to.eventually.equal('no')
})
it('should support if 4', function () {
it('should support >=', function () {
var src = '{% if 1>=2 and one<two %}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('')
.to.eventually.equal('')
})
it('should support if 5', function () {
it('should support !=', function () {
var src = '{% if one!=two %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('yes')
.to.eventually.equal('yes')
})
it('should support if 6', function () {
it('should support boolean', function () {
var src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2')
.to.eventually.equal('2')
})
it('should support if 7', function () {
it('should support nested', function () {
var src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('')
.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')
.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')
.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')
.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')
.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')
.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')
.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')
.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')
.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')
.to.eventually.equal('no')
})
})
+3 -3
View File
@@ -12,13 +12,13 @@ describe('tags/increment', function () {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2')
.to.eventually.equal('2')
})
it('should increment undefined', function () {
var src = '{% increment empty %}{{empty}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('1')
.to.eventually.equal('1')
})
it('should support increment multiple times', function () {
@@ -27,6 +27,6 @@ describe('tags/increment', function () {
foo: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('3')
.to.eventually.equal('3')
})
})
+2 -2
View File
@@ -22,7 +22,7 @@ describe('tags/layout', function () {
})
var src = '{% layout "parent" %}{%block%}A'
return expect(liquid.parseAndRender(src)).to
.be.rejectedWith(/tag {%block%} not closed/)
.be.rejectedWith(/tag {%block%} not closed/)
})
it('should handle anonymous block', function () {
mock({
@@ -30,7 +30,7 @@ describe('tags/layout', function () {
})
var src = '{% layout "parent.html" %}{%block%}A{%endblock%}'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAY')
.eventually.equal('XAY')
})
it('should handle named blocks', function () {
mock({
+3 -3
View File
@@ -7,18 +7,18 @@ describe('tags/raw', function () {
var liquid = Liquid()
it('should support raw 1', function () {
return expect(liquid.parseAndRender('{% raw%}'))
.to.be.rejectedWith(/{% raw%} not closed/)
.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)
.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)
.to.eventually.equal(dst)
})
})
+21 -15
View File
@@ -12,9 +12,9 @@ describe('tags/tablerow', function () {
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>'
'<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)
})
@@ -24,47 +24,53 @@ describe('tags/tablerow', function () {
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
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 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/)
.to.be.rejectedWith(/tag .* not closed/)
})
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>'
'<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('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/)
.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/)
.to.be.rejectedWith(/illegal cols: undefined/)
})
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>'
'<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>'
'<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>' +
'</table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
})
+6 -6
View File
@@ -7,29 +7,29 @@ describe('tags/unless', function () {
var liquid = Liquid()
it('should render else when predicate yields true', function () {
// 0 is truthy
// 0 is truthy
var src = '{% unless 0 %}yes{%else%}no{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('no')
.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')
.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/)
.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')
.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('')
.to.eventually.equal('')
})
})
+7 -49
View File
@@ -1,6 +1,5 @@
const chai = require('chai')
const parse = require('../src/tokenizer.js').parse
const whiteSpaceCtrl = require('../src/tokenizer.js').whiteSpaceCtrl
const expect = chai.expect
describe('tokenizer', function () {
@@ -16,7 +15,7 @@ describe('tokenizer', function () {
it('should throw when non-string passed in', function () {
expect(function () {
parse({})
}).to.throw('illegal input type')
}).to.throw('illegal input')
})
it('should handle tag syntax', function () {
var html = '<p>{% for p in a[1]%}</p>'
@@ -26,20 +25,20 @@ describe('tokenizer', function () {
expect(tokens[1].type).to.equal('tag')
expect(tokens[1].value).to.equal('for p in a[1]')
})
it('should handle output syntax', function () {
it('should handle value syntax', function () {
var html = '<p>{{foo | date: "%Y-%m-%d"}}</p>'
var tokens = parse(html)
expect(tokens.length).to.equal(3)
expect(tokens[1].type).to.equal('output')
expect(tokens[1].type).to.equal('value')
expect(tokens[1].value).to.equal('foo | date: "%Y-%m-%d"')
})
it('should handle successive outputs and tags', function () {
it('should handle consecutive value and tags', function () {
var html = '{{foo}}{{bar}}{%foo%}{%bar%}'
var tokens = parse(html)
expect(tokens.length).to.equal(4)
expect(tokens[0].type).to.equal('output')
expect(tokens[0].type).to.equal('value')
expect(tokens[3].type).to.equal('tag')
expect(tokens[1].value).to.equal('bar')
@@ -62,53 +61,12 @@ describe('tokenizer', function () {
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 () {
it('should handle multiple lines value', 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].type).to.equal('value')
expect(tokens[0].raw).to.equal('{{foo\n|date:\n"%Y-%m-%d"\n}}')
})
})
describe('whitespace control', function () {
it('should not strip by default', function () {
expect(whiteSpaceCtrl('\n {%foo%} \n')).to.equal('\n {%foo%} \n')
})
it('should strip all blank characters before and after', function () {
expect(whiteSpaceCtrl(' \t\r{%-foo-%} \t\n')).to.equal('{%-foo-%}')
})
it('should not trim previous/next lines', 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', function () {
expect(whiteSpaceCtrl('{%-foo-%} \n\n')).to.equal('{%-foo-%}\n')
})
it('should trim all leading/trailing blanks when options.greedy set', function () {
expect(whiteSpaceCtrl(' \n \n\t\r{%-foo-%}\n \n', {
greedy: true
})).to.equal('{%-foo-%}')
})
it('should strip whitespaces when set trim_left', function () {
expect(whiteSpaceCtrl('\n {%foo%} \n', {
trim_left: true
})).to.equal('\n{%-foo%} \n')
})
it('should strip whitespaces when set trim_right', function () {
expect(whiteSpaceCtrl('\n {%foo%} \n', {
trim_right: true
})).to.equal('\n {%foo-%}')
})
it('markup should has priority over options', function () {
expect(whiteSpaceCtrl('\n {%-foo%} \n', {
trim_left: false
})).to.equal('\n{%-foo%} \n')
})
it('should support a mix of markup and options', 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/)
})
})
+162 -158
View File
@@ -17,11 +17,11 @@ describe('error', function () {
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')
})
.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']
@@ -30,39 +30,52 @@ describe('error', function () {
' 2| 2nd',
'>> 3| X{% . a %} Y',
' 4| 4th',
'TokenizationError: illegal tag syntax'
'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')
})
.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)
})
.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)
})
.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')
})
.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'
@@ -70,12 +83,12 @@ describe('error', function () {
'/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')
})
.be.rejected
.then(function (err) {
mock.restore()
expect(err.name).to.equal('TokenizationError')
expect(err.file).to.equal('/foo.html')
})
})
})
@@ -101,40 +114,40 @@ describe('error', function () {
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')
})
.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')
})
.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')
})
.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')
})
.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']
@@ -145,15 +158,15 @@ describe('error', function () {
' 5| 5th',
' 6| 6th',
' 7| 7th',
'Error: intended render error'
'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')
})
.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({
@@ -175,17 +188,17 @@ describe('error', function () {
' 5| 5th',
' 6| {%block%}{%endblock%}',
' 7| 7th',
'Error: intended render error'
'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')
})
.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']
@@ -200,41 +213,41 @@ describe('error', function () {
' 5| 5th',
' 6| 6th',
' 7| 7th',
'Error: intended render error'
'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')
})
.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')
})
.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')
})
.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.match(/at .*:\d+:\d+\)/)
})
.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 () {
@@ -243,12 +256,12 @@ describe('error', function () {
'/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')
})
.be.rejected
.then(function (err) {
mock.restore()
expect(err.name).to.equal('RenderError')
expect(err.file).to.equal('/foo.html')
})
})
})
@@ -263,46 +276,46 @@ describe('error', function () {
})
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')
})
.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')
})
.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')
})
.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')
})
.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')
})
.be.rejected
.then(function (err) {
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag a not found')
})
})
it('should contain template context in err.stack', function () {
@@ -314,15 +327,15 @@ describe('error', function () {
' 5| 5th',
' 6| 6th',
' 7| 7th',
'AssertionError: tag a not found'
'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')
})
.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 () {
@@ -332,41 +345,32 @@ describe('error', function () {
'>> 2| X{% a %} {% enda %} Y',
' 3| 3rd',
' 4| 4th',
'AssertionError: tag a not found'
'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)
})
.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 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)
})
.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('AssertionError: tag -a not found')
expect(err.stack).to.match(/at .*:\d+:\d+\)/)
})
.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 file path in err.file', function () {
@@ -375,12 +379,12 @@ describe('error', function () {
'/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')
})
.be.rejected
.then(function (err) {
mock.restore()
expect(err.name).to.equal('ParseError')
expect(err.file).to.equal('/foo.html')
})
})
})
})
+12 -12
View File
@@ -13,18 +13,18 @@ describe('util/promise', function () {
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')
}
}))
['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 () {
+33 -7
View File
@@ -8,8 +8,8 @@ describe('util/strftime', function () {
var then
before(function () {
mockUTC()
now = new Date('2016-01-04T13:15:23')
then = new Date('2016-03-06T03:05:03')
now = new Date('2016-01-04T13:15:23.000Z')
then = new Date('2016-03-06T03:05:03.000Z')
})
after(function () {
restoreUTC()
@@ -36,8 +36,22 @@ describe('util/strftime', function () {
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 %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')
@@ -45,6 +59,10 @@ describe('util/strftime', function () {
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')
})
@@ -57,9 +75,9 @@ describe('util/strftime', function () {
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')
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')
@@ -94,9 +112,17 @@ describe('util/strftime', function () {
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 () {
+5 -7
View File
@@ -62,14 +62,12 @@ describe('util/underscore', function () {
expect(spy).to.have.been.calledOnce
})
})
describe('.echo()', function () {
it('should be transparent', function () {
expect(_.echo('foo')('bar')).to.equal('bar')
describe('.range()', function () {
it('should return a range of integers', function () {
expect(_.range(3, 5)).to.deep.equal([3, 4])
})
it('should log the arguments', function () {
var log = sinon.spy(console, 'log')
_.echo('foo')('bar')
expect(log).to.have.been.calledWith('[foo]', 'bar')
it('should treat start as 0 if omitted', function () {
expect(_.range(3)).to.deep.equal([0, 1, 2])
})
})
describe('.assign()', function () {
+448
View File
@@ -0,0 +1,448 @@
const chai = require('chai')
const expect = chai.expect
const Liquid = require('..')
const liquid = new Liquid()
chai.use(require('chai-as-promised'))
const cases = [
{
text: `
<div>
<p>
{{ 'John' }}
</p>
</div>
`,
expected: `
<div>
<p>
John
</p>
</div>
`
}, {
text: `
<div>
<p>
{{- 'John' -}}
</p>
</div>
`,
expected: `
<div>
<p>John</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if true -%}
yes
{%- endif -%}
</p>
</div>
`,
expected: `
<div>
<p>yes</p>
</div>
`
}, {
text: `
<div>
<p>
{% if true %}
yes
{% endif %}
</p>
</div>
`,
expected: `
<div>
<p>
yes
</p>
</div>
`
}, {
text: `
<div>
<p>
{% if false %}
no
{% endif %}
</p>
</div>
`,
expected: `
<div>
<p>
</p>
</div>
`
}, {
text: '<p>{{- \'John\' -}}</p>',
expected: '<p>John</p>'
}, {
text: '<p>{%- if true -%}yes{%- endif -%}</p>',
expected: '<p>yes</p>'
}, {
text: '<p>{%- if false -%}no{%- endif -%}</p>',
expected: '<p></p>'
}, {
text: '<p> {%- if true %} yes {% endif -%} </p>',
expected: '<p> yes </p>'
}, {
text: '<p> {%- if false %} no {% endif -%} </p>',
expected: '<p></p>'
}, {
text: '<p> {% if true -%} yes {%- endif %} </p>',
expected: '<p> yes </p>'
}, {
text: '<p> {% if false -%} no {%- endif %} </p>',
expected: '<p> </p>'
}, {
text: '<p> {% if true -%} yes {% endif -%} </p>',
expected: '<p> yes </p>'
}, {
text: '<p> {% if false -%} no {% endif -%} </p>',
expected: '<p> </p>'
}, {
text: '<p> {%- if true %} yes {%- endif %} </p>',
expected: '<p> yes </p>'
}, {
text: '<p> {%- if false %} no {%- endif %} </p>',
expected: '<p> </p>'
}, {
text: `
<div>
<p>
{{- 'John' }}
</p>
</div>
`,
expected: `
<div>
<p>John
</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if true %}
yes
{%- endif %}
</p>
</div>
`,
expected: `
<div>
<p>
yes
</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if false %}
no
{%- endif %}
</p>
</div>
`,
expected: `
<div>
<p>
</p>
</div>
`
}, {
text: `
<div>
<p>
{{ 'John' -}}
</p>
</div>
`,
expected: `
<div>
<p>
John</p>
</div>
`
}, {
text: `
<div>
<p>
{% if true -%}
yes
{% endif -%}
</p>
</div>
`,
expected: `
<div>
<p>
yes
</p>
</div>
`
}, {
text: `
<div>
<p>
{% if false -%}
no
{% endif -%}
</p>
</div>
`,
expected: `
<div>
<p>
</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if true %}
yes
{% endif -%}
</p>
</div>
`,
expected: `
<div>
<p>
yes
</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if false %}
no
{% endif -%}
</p>
</div>
`,
expected: `
<div>
<p></p>
</div>
`
}, {
text: `
<div>
<p>
{% if true -%}
yes
{%- endif %}
</p>
</div>
`,
expected: `
<div>
<p>
yes
</p>
</div>
`
}, {
text: `
<div>
<p>
{% if false -%}
no
{%- endif %}
</p>
</div>
`,
expected: `
<div>
<p>
</p>
</div>
`
}, {
text: `
<div>
<p>
{{- 'John' -}}
</p>
</div>
`,
expected: `
<div>
<p>John</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if true -%}
yes
{%- endif -%}
</p>
</div>
`,
expected: `
<div>
<p>yes</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if false -%}
no
{%- endif -%}
</p>
</div>
`,
expected: `
<div>
<p></p>
</div>
`
}, {
text: `
<div>
<p>
{{- 'John' -}},
{{- '30' -}}
</p>
</div>
`,
expected: `
<div>
<p>John,30</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if true -%}
yes
{%- endif -%}
</p>
</div>
`,
expected: `
<div>
<p>yes</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if false -%}
no
{%- endif -%}
</p>
</div>
`,
expected: `
<div>
<p></p>
</div>
`
}, {
text: `
<div>
<p>
{{- 'John' -}}
{{- '30' -}}
</p>
<b>
{{ 'John' -}}
{{- '30' }}
</b>
<i>
{{- 'John' }}
{{ '30' -}}
</i>
</div>
`,
expected: `
<div>
<p>John30</p>
<b>
John30
</b>
<i>John
30</i>
</div>
`
}, {
text: `
<div>
{%- if true -%}
{%- if true -%}
<p>
{{- 'John' -}}
</p>
{%- endif -%}
{%- endif -%}
</div>
`,
expected: `
<div><p>John</p></div>
`
}, {
text: `
<div>
{% raw %}
{%- if true -%}
<p>
{{- 'John' -}}
</p>
{%- endif -%}
{% endraw %}
</div>
`,
expected: `
<div>
{%- if true -%}
<p>
{{- 'John' -}}
</p>
{%- endif -%}
</div>
`
}
]
describe('Whitespace Control', function () {
cases.forEach(item => it(
item.text,
() => expect(liquid.parseAndRender(item.text)).to.eventually.equal(item.expected)
))
})