mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-15 04:10:40 -07:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6755462056 | ||
|
|
02806b2257 | ||
|
|
d0fb5ccece | ||
|
|
b7144f9b75 | ||
|
|
88fc05732f | ||
|
|
44b1aac096 | ||
|
|
42043b6944 | ||
|
|
61f146432d | ||
|
|
220b705b73 | ||
|
|
ef85bd9192 | ||
|
|
8e9e10fdb4 | ||
|
|
f668a5cc41 | ||
|
|
098f5164e7 | ||
|
|
432f878bb6 | ||
|
|
aa54dad36e | ||
|
|
c6ff1f7911 | ||
|
|
11355cbf09 | ||
|
|
7ccd0cb1e5 | ||
|
|
4326c223f3 | ||
|
|
78b6e35fbf | ||
|
|
e275368cb3 | ||
|
|
ca2b16a583 | ||
|
|
86d0529a5e | ||
|
|
400b93c88d | ||
|
|
22b41fd1a8 | ||
|
|
d7c7f32d4b | ||
|
|
925df9a9b5 | ||
|
|
7b696ed0d2 | ||
|
|
c55f0234eb | ||
|
|
eee5649a47 | ||
|
|
1048f4e0ab | ||
|
|
5c6d05092f | ||
|
|
900664a26d | ||
|
|
757a06ee83 | ||
|
|
9f6e9f2f3f | ||
|
|
0f9adfb067 | ||
|
|
dabde0e9e4 | ||
|
|
bd4e851b3c | ||
|
|
1d2aece687 | ||
|
|
ace271c7f0 | ||
|
|
4cbfa6d204 | ||
|
|
3153f1d4bb | ||
|
|
9cd4f3d904 | ||
|
|
8dd1b3ba99 | ||
|
|
11de73a7b1 | ||
|
|
0325eacddf | ||
|
|
a21fcf6f87 | ||
|
|
7bb2ee2213 | ||
|
|
b24582c2c4 | ||
|
|
49cb7a8c36 | ||
|
|
a4126e7f10 | ||
|
|
5196d6ad56 | ||
|
|
6082bf4757 | ||
|
|
8efb41a631 | ||
|
|
d348edac14 | ||
|
|
be00f1d385 | ||
|
|
4e132ca1c5 | ||
|
|
329aea6bd6 | ||
|
|
23e7424f9d | ||
|
|
8241625be4 | ||
|
|
d36ec17621 | ||
|
|
485424cc89 | ||
|
|
a239389044 | ||
|
|
e8fa8d32f5 | ||
|
|
502426f621 | ||
|
|
8c77fc5a3d | ||
|
|
be17d7443c | ||
|
|
118624ca7d | ||
|
|
d08ad6dc97 | ||
|
|
e22870f5d7 | ||
|
|
bd6706cf4d | ||
|
|
b71928ffd4 | ||
|
|
6f69cd774d | ||
|
|
1b662d374d | ||
|
|
6dd6ed176c | ||
|
|
21af8c4d7a | ||
|
|
942a3224a1 | ||
|
|
11259fae62 | ||
|
|
030037eedc | ||
|
|
6d59f34fc8 | ||
|
|
72597c52e5 | ||
|
|
7904f823a8 | ||
|
|
e993118e87 | ||
|
|
4ae63b2899 | ||
|
|
9f446ad024 | ||
|
|
6f82b914cb | ||
|
|
31397a4862 | ||
|
|
a2a076d038 | ||
|
|
3dc37bf980 | ||
|
|
4ee2bc964c | ||
|
|
ea2a5f5c3b | ||
|
|
52e2be68ab | ||
|
|
cbde48971a | ||
|
|
e91cc8c950 | ||
|
|
314aa6b467 | ||
|
|
14e53ed3a9 | ||
|
|
cf6d3e78fe | ||
|
|
fb52c864b1 | ||
|
|
9f82aec569 | ||
|
|
29fe8dcb4b | ||
|
|
2a16800305 | ||
|
|
154cf379a8 | ||
|
|
ed20fe6072 | ||
|
|
2632e3e97e | ||
|
|
82f84d96c1 | ||
|
|
1126dffd7d | ||
|
|
07ec997ffd | ||
|
|
79815784c1 | ||
|
|
2d793a63fe | ||
|
|
cc2b2ea5d1 | ||
|
|
8ff9eeb51d | ||
|
|
3bc7caa387 | ||
|
|
20044c4256 | ||
|
|
e72f295bd0 | ||
|
|
66774865f4 | ||
|
|
2ae6874397 | ||
|
|
b307f6ffd0 | ||
|
|
5b5db616e2 | ||
|
|
551a15f373 | ||
|
|
45e0fb21dc | ||
|
|
4fc977268f | ||
|
|
8231727428 | ||
|
|
0a068ac51c | ||
|
|
6f1d6f3d05 | ||
|
|
aa52a31e90 | ||
|
|
e4056a79ee | ||
|
|
f1d68409b1 | ||
|
|
7ad9ce95e9 | ||
|
|
ea7e334d87 | ||
|
|
4f123c1d6b | ||
|
|
0f4edc5b53 | ||
|
|
48bee428d5 | ||
|
|
2d1f05799f | ||
|
|
dbc18539a0 | ||
|
|
492f56cbfb | ||
|
|
4018ffe68b | ||
|
|
21eefe1d7b | ||
|
|
0c8148c12b | ||
|
|
7f336ded5c | ||
|
|
5ecca1b761 | ||
|
|
af284daf34 | ||
|
|
21a5ac7e08 | ||
|
|
7d22214cb5 | ||
|
|
d6ca12f3bd | ||
|
|
84f7a399c5 | ||
|
|
5b5dfd5c00 | ||
|
|
d032f7f4d4 | ||
|
|
044035b8ed | ||
|
|
564d9cd9f4 | ||
|
|
fbb1dc8a36 | ||
|
|
c99dfd69e7 | ||
|
|
4719544d49 | ||
|
|
2c0ba9bfd9 | ||
|
|
89636736a4 | ||
|
|
deca9677dd | ||
|
|
543368ed89 | ||
|
|
dcd7b01fa4 | ||
|
|
209d3910ab | ||
|
|
40bdd7e94a | ||
|
|
03b7ee95ed | ||
|
|
64e9cb7044 | ||
|
|
20af0c489e | ||
|
|
2bc53a3850 | ||
|
|
3a450bba1b | ||
|
|
397b2e48b6 | ||
|
|
d89e9a214b | ||
|
|
a6f915ce42 |
@@ -0,0 +1,3 @@
|
||||
node_modules
|
||||
dist
|
||||
coverage
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "standard",
|
||||
"env": {
|
||||
"browser": true,
|
||||
"node": true
|
||||
},
|
||||
"plugins": [
|
||||
"standard",
|
||||
"promise"
|
||||
]
|
||||
}
|
||||
@@ -38,3 +38,4 @@ jspm_packages
|
||||
|
||||
# vim
|
||||
.*.swp
|
||||
package-lock.json
|
||||
|
||||
+3
-1
@@ -1,7 +1,9 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- "8"
|
||||
- "6"
|
||||
- "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
|
||||
|
||||
@@ -1,128 +1,124 @@
|
||||
# shopify-liquid
|
||||
# liquidjs
|
||||
|
||||
[](https://www.npmjs.org/package/shopify-liquid)
|
||||
[](https://travis-ci.org/harttle/shopify-liquid)
|
||||
[](https://coveralls.io/github/harttle/shopify-liquid?branch=master)
|
||||
[](https://david-dm.org/harttle/shopify-liquid)
|
||||
[](https://www.npmjs.org/package/liquidjs)
|
||||
[](https://www.npmjs.org/package/liquidjs)
|
||||
[](https://travis-ci.org/harttle/liquidjs)
|
||||
[](https://coveralls.io/github/harttle/liquidjs?branch=master)
|
||||
[](https://github.com/harttle/liquidjs/issues)
|
||||
[](https://github.com/harttle/liquidjs/graphs/contributors)
|
||||
[](https://david-dm.org/harttle/liquidjs)
|
||||
[](https://david-dm.org/harttle/liquidjs?type=dev)
|
||||
[](https://github.com/harttle/liquidjs/blob/master/LICENSE)
|
||||
|
||||
A feature-rich [Liquid][shopify-liquid] implementation for Node.js, with compliance with [Jekyll][jekyll] and [Github Pages][gh].
|
||||
See:
|
||||
This is a liquid implementation for both Node.js and browsers. Website: <http://harttle.github.io/liquidjs/>, Live Demo: <https://jsfiddle.net/6u40xbzs/>
|
||||
|
||||
* [supported filter list](https://github.com/harttle/shopify-liquid/wiki/Builtin-Filters), and
|
||||
* [supported tag list](https://github.com/harttle/shopify-liquid/wiki/Builtin-Tags)
|
||||
* any-promise
|
||||
**Features**
|
||||
|
||||
Installation:
|
||||
* Fully compatible to [shopify][shopify/liquid], with all [tags][tags] and [filters][filters] implemented
|
||||
* Support layout(extend) and include syntax
|
||||
* In pure JavaScript with Promise-based API
|
||||
|
||||
```bash
|
||||
npm install --save shopify-liquid
|
||||
```
|
||||
**Differences**
|
||||
|
||||
Though being compatible with [Ruby Liquid](https://github.com/shopify/liquid) is one of our priorities, there're still certain differences. You may need some configuration to get it compatible in these senarios:
|
||||
|
||||
* Dynamic file locating (enabled by default), which means layout/partial name can be an variable in liquidjs. See [#51](https://github.com/harttle/liquidjs/issues/51).
|
||||
* Truthy and Falsy. All values except `undefined`, `null`, `false` are truthy, whereas in Ruby Liquid all except `nil` and `false` are truthy. See [#26](https://github.com/harttle/liquidjs/pull/26).
|
||||
* Number Rendering. Since JavaScript do not distinguish `float` and `integer`, we cannot either convert between them nor render regarding to their type. See [#59](https://github.com/harttle/liquidjs/issues/59).
|
||||
|
||||
## TOC
|
||||
|
||||
* Usage
|
||||
* [Render from String](#render-from-string)
|
||||
* [Render from File](#render-from-file)
|
||||
* [Use with Express.js](#use-with-expressjs)
|
||||
* [Use in Browser](#use-in-browser)
|
||||
* [Include Partials](#include-partials)
|
||||
* [Layout Templates (Extends)](#layout-templates-extends)
|
||||
* API Spec
|
||||
* [Constructor Options](#options)
|
||||
* [Register Filters](#register-filters), [Builtin Filters](https://github.com/harttle/liquidjs/wiki/Builtin-Filters)
|
||||
* [Register Tags](#register-tags), [Builtin Tags](https://github.com/harttle/liquidjs/wiki/Builtin-Tags)
|
||||
* [Operators](https://github.com/harttle/liquidjs/wiki/Operators)
|
||||
* [Whitespace Control](https://github.com/harttle/liquidjs/wiki/Whitespace-Control)
|
||||
|
||||
## Render from String
|
||||
|
||||
Install as Node.js dependency:
|
||||
|
||||
```bash
|
||||
# You'll need a promise-polyfill for Node.js < 4
|
||||
npm install --save liquidjs
|
||||
```
|
||||
|
||||
Parse and Render:
|
||||
|
||||
```javascript
|
||||
var Liquid = require('shopify-liquid');
|
||||
var Liquid = require('liquidjs');
|
||||
var engine = Liquid();
|
||||
|
||||
engine.parseAndRender('{{name | capitalize}}', {name: 'alice'})
|
||||
.then(function(html){
|
||||
// html === 'Alice'
|
||||
});
|
||||
engine
|
||||
.parseAndRender('{{name | capitalize}}', {name: 'alice'})
|
||||
.then(console.log);
|
||||
|
||||
// outputs 'Alice'
|
||||
```
|
||||
|
||||
Caching templates:
|
||||
|
||||
```javascript
|
||||
var tpl = engine.parse('{{name | capitalize}}');
|
||||
engine.render(tpl, {name: 'alice'})
|
||||
.then(function(html){
|
||||
// html === 'Alice'
|
||||
});
|
||||
engine
|
||||
.render(tpl, {name: 'alice'})
|
||||
.then(console.log);
|
||||
|
||||
// outputs 'Alice'
|
||||
```
|
||||
|
||||
## Render from File
|
||||
|
||||
```javascript
|
||||
var engine = Liquid({
|
||||
root: path.resolve(__dirname, 'views/'), // for layouts and includes
|
||||
extname: '.liquid',
|
||||
cache: false,
|
||||
strict_filters: false, // default: false
|
||||
strict_variables: false // default: false
|
||||
root: path.resolve(__dirname, 'views/'), // dirs to lookup layouts/includes
|
||||
extname: '.liquid' // the extname used for layouts/includes, defaults ""
|
||||
});
|
||||
engine.renderFile("hello.liquid", {name: 'alice'})
|
||||
.then(function(html){
|
||||
// html === 'Alice'
|
||||
});
|
||||
// equivalent to:
|
||||
engine.renderFile("hello", {name: 'alice'})
|
||||
.then(function(html){
|
||||
// html === 'Alice'
|
||||
});
|
||||
.then(console.log) // outputs "Alice"
|
||||
|
||||
// which is equivalent to:
|
||||
engine
|
||||
.renderFile("hello", {name: 'alice'})
|
||||
.then(console.log) // outputs "Alice"
|
||||
```
|
||||
|
||||
* `root` is a directory or an array of directories to resolve layouts and includes, as well as the filename passed in when calling `.renderFile()`.
|
||||
If an array, the files are looked up in the order they occur in the array.
|
||||
Defaults to `process.cwd()`
|
||||
|
||||
* `extname` is used to lookup the template file when filepath doesn't include an extension name. Defaults to `.liquid`
|
||||
|
||||
* `cache` indicates whether or not to cache resolved templates. Defaults to `false`.
|
||||
|
||||
* `strict_filters` is used to enable strict filter existence. If set to `false`, undefined filters will be rendered as empty string. Otherwise, undefined filters will cause an exception. Defaults to `false`.
|
||||
|
||||
* `strict_variables` is used to enable strict variable derivation.
|
||||
If set to `false`, undefined variables will be rendered as empty string.
|
||||
Otherwise, undefined variables will cause an exception. Defaults to `false`.
|
||||
|
||||
## Use with Express.js
|
||||
|
||||
```javascript
|
||||
// register liquid engine
|
||||
app.engine('liquid', engine.express({
|
||||
strict_variables: true, // Default: fasle
|
||||
strict_filters: true // Default: false
|
||||
}));
|
||||
app.engine('liquid', engine.express());
|
||||
app.set('views', './views'); // specify the views directory
|
||||
app.set('view engine', 'liquid'); // set to default
|
||||
```
|
||||
|
||||
> There's an Express demo [here](demo/express/).
|
||||
|
||||
When using with Express.js, partials(includes and layouts) will be looked up in
|
||||
both Liquid `root` and Express `views` directories.
|
||||
[Here](demo/express/)'s an Express demo. When used with Express.js,
|
||||
Express [`views`][express-views] will be included when looking up
|
||||
partials(includes and layouts).
|
||||
|
||||
## Use in Browser
|
||||
|
||||
[Download][releases] the dist files and import into your HTML.
|
||||
And `window.Liquid` is what you want. There's also a [demo](demo/browser/).
|
||||
You can get a dist file for browsers from
|
||||
|
||||
```html
|
||||
<html lang="en">
|
||||
<head>
|
||||
<script src="dist/liquid.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
var engine = window.Liquid();
|
||||
var src = '{{ name | capitalize}}';
|
||||
var ctx = {
|
||||
name: 'welcome to Shopify Liquid'
|
||||
};
|
||||
engine.parseAndRender(src, ctx)
|
||||
.then(function(html) {
|
||||
// html === Welcome to Shopify Liquid
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
* [Releases][releases] page for liquidjs, or
|
||||
* unpkg.com: <https://unpkg.com/liquidjs/dist/liquid.min.js>
|
||||
|
||||
Note: any-promise browser requires a polyfill or explicit registration. e.g: `require('any-promise/register/bluebird')`
|
||||
Here's the demo:
|
||||
|
||||
## Includes
|
||||
* JSFiddle: <https://jsfiddle.net/6u40xbzs/>
|
||||
* Demo directory: [/demo/browser/](demo/browser/).
|
||||
|
||||
Note: For [IE and Android UC][caniuse-promises] browser, you will need a [Promise polyfill][pp].
|
||||
|
||||
## Include Partials
|
||||
|
||||
```
|
||||
// file: color.liquid
|
||||
@@ -143,7 +139,7 @@ color: 'red' shape: 'circle'
|
||||
color: 'yellow' shape: 'square'
|
||||
```
|
||||
|
||||
## Layouts
|
||||
## Layout Templates (Extends)
|
||||
|
||||
```
|
||||
// file: default-layout.liquid
|
||||
@@ -167,16 +163,51 @@ Footer
|
||||
* It's possible to define multiple blocks.
|
||||
* block name is optional when there's only one block.
|
||||
|
||||
## Options
|
||||
|
||||
The full list of options for `Liquid()` is listed as following:
|
||||
|
||||
* `root` is a directory or an array of directories to resolve layouts and includes, as well as the filename passed in when calling `.renderFile()`.
|
||||
If an array, the files are looked up in the order they occur in the array.
|
||||
Defaults to `["."]`
|
||||
|
||||
* `extname` is used to lookup the template file when filepath doesn't include an extension name. Eg: setting to `".html"` will allow including file by basename. Defaults to `""`.
|
||||
|
||||
* `cache` indicates whether or not to cache resolved templates. Defaults to `false`.
|
||||
|
||||
* `dynamicPartials`: if set, treat `<filepath>` parameter in `{%include filepath %}`, `{%layout filepath%}` as a variable, otherwise as a literal value. Defaults to `true`.
|
||||
|
||||
* `strict_filters` is used to enable strict filter existence. If set to `false`, undefined filters will be rendered as empty string. Otherwise, undefined filters will cause an exception. Defaults to `false`.
|
||||
|
||||
* `strict_variables` is used to enable strict variable derivation.
|
||||
If set to `false`, undefined variables will be rendered as empty string.
|
||||
Otherwise, undefined variables will cause an exception. 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_tag_left` is similiar to `trim_tag_right`, whereas the `\n` is exclusive. Defaults to `false`. See [Whitespace Control][whitespace control] for details.
|
||||
|
||||
* `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`.
|
||||
|
||||
## Register Filters
|
||||
|
||||
```javascript
|
||||
// Usage: {{ name | uppper }}
|
||||
engine.registerFilter('upper', function(v){
|
||||
return v.toUpperCase();
|
||||
});
|
||||
engine.registerFilter('upper', v => v.toUpperCase())
|
||||
```
|
||||
|
||||
> See existing filter implementations: <https://github.com/harttle/shopify-liquid/blob/master/filters.js>
|
||||
Filter arguments will be passed to the registered filter function, for example:
|
||||
|
||||
```javascript
|
||||
// Usage: {{ 1 | add: 2, 3 }}
|
||||
engine.registerFilter('add', (initial, arg1, arg2) => initial + arg1 + arg2)
|
||||
```
|
||||
|
||||
See existing filter implementations here: <https://github.com/harttle/liquidjs/blob/master/filters.js>
|
||||
|
||||
## Register Tags
|
||||
|
||||
@@ -193,18 +224,22 @@ engine.registerTag('upper', {
|
||||
});
|
||||
```
|
||||
|
||||
> See existing tag implementations: <https://github.com/harttle/shopify-liquid/blob/master/tags/>
|
||||
* `parse`: Read tokens from `remainTokens` until your end token.
|
||||
* `render`: Combine scope data with your parsed tokens into HTML string.
|
||||
|
||||
## Contribution Guide
|
||||
|
||||
1. Make a fork.
|
||||
2. Write a test to demonstrate your feature is not supported yet.
|
||||
3. Optionaly, change source files to make all test pass.
|
||||
4. Create a pull request.
|
||||
See existing tag implementations here: <https://github.com/harttle/liquidjs/blob/master/tags/>
|
||||
|
||||
[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/liquidjs/tree/master/test
|
||||
[caniuse-promises]: http://caniuse.com/#feat=promises
|
||||
[whitespace control]: https://github.com/harttle/liquidjs/wiki/Whitespace-Control
|
||||
[tags]: https://github.com/harttle/liquidjs/wiki/Builtin-Tags
|
||||
[filters]: https://github.com/harttle/liquidjs/wiki/Builtin-Filters
|
||||
[express-views]: http://expressjs.com/en/guide/using-template-engines.html
|
||||
[pp]: https://github.com/taylorhakes/promise-polyfill
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
access time: {{date|date: "%Y-%m-%d %H:%M:%S"}}
|
||||
@@ -0,0 +1 @@
|
||||
<h2>Welcome to {{ name | capitalize}}, {% include 'date.html' %}</h2>
|
||||
+12
-6
@@ -8,19 +8,25 @@
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h2 id="header"></h2>
|
||||
<script>
|
||||
var engine = window.Liquid();
|
||||
|
||||
var src = 'Welcome to {{ name | capitalize}}, ' +
|
||||
'access time: {{date|date: "%Y-%m-%d %H:%M:%S"}}';
|
||||
var engine = window.Liquid({
|
||||
// root: './',
|
||||
extname: '.html',
|
||||
cache: true
|
||||
});
|
||||
var src = '<h2>Welcome to {{ name | capitalize}}, ' +
|
||||
'access time: {{date|date: "%Y-%m-%d %H:%M:%S"}}</h2>';
|
||||
var ctx = {
|
||||
name: 'Liquid',
|
||||
date: new Date()
|
||||
};
|
||||
engine.parseAndRender(src, ctx)
|
||||
.then(function(html) {
|
||||
document.getElementById('header').innerHTML = html;
|
||||
document.body.innerHTML += html
|
||||
return engine.renderFile('hello', ctx);
|
||||
})
|
||||
.then(function(html) {
|
||||
document.body.innerHTML += html
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
+16
-16
@@ -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
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
const app = require('./app.js');
|
||||
const app = require('./app.js')
|
||||
|
||||
app.listen(3000, function () {
|
||||
console.log('Example app listening on port 3000!');
|
||||
});
|
||||
|
||||
console.log('Example app listening on port 3000!')
|
||||
})
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% layout 'layout' %}
|
||||
|
||||
<ul>
|
||||
{% for todo in todolist %}
|
||||
{% for todo in todos %}
|
||||
<li>{% include 'todo' id=forloop.index %}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
|
||||
Vendored
+1947
-1806
File diff suppressed because it is too large
Load Diff
Vendored
+1
-2
File diff suppressed because one or more lines are too long
+117
-107
@@ -1,127 +1,137 @@
|
||||
const strftime = require('./src/util/strftime.js');
|
||||
const _ = require('./src/util/underscore.js');
|
||||
const strftime = require('./src/util/strftime.js')
|
||||
const _ = require('./src/util/underscore.js')
|
||||
const isTruthy = require('./src/syntax.js').isTruthy
|
||||
|
||||
var escapeMap = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
};
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": '''
|
||||
}
|
||||
var unescapeMap = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
''': "'",
|
||||
};
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
''': "'"
|
||||
}
|
||||
|
||||
var filters = {
|
||||
'abs': v => Math.abs(v),
|
||||
'append': (v, arg) => v + arg,
|
||||
'capitalize': str => stringify(str).charAt(0).toUpperCase() + str.slice(1),
|
||||
'ceil': v => Math.ceil(v),
|
||||
'date': (v, arg) => {
|
||||
if (v === 'now') v = new Date();
|
||||
return strftime(v, arg);
|
||||
},
|
||||
'default': (v, arg) => arg || v,
|
||||
'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) => {
|
||||
var date = v
|
||||
if (v === 'now') {
|
||||
date = new Date()
|
||||
} else if (_.isString(v)) {
|
||||
date = new Date(v)
|
||||
}
|
||||
return isValidDate(date) ? strftime(date, arg) : v
|
||||
},
|
||||
'default': (v, arg) => isTruthy(v) ? v : arg,
|
||||
'divided_by': (v, arg) => v / arg,
|
||||
'downcase': v => v.toLowerCase(),
|
||||
'escape': escape,
|
||||
|
||||
'escape_once': str => escape(unescape(str)),
|
||||
'first': v => v[0],
|
||||
'floor': v => Math.floor(v),
|
||||
'join': (v, arg) => v.join(arg),
|
||||
'last': v => v[v.length - 1],
|
||||
'lstrip': v => stringify(v).replace(/^\s+/, ''),
|
||||
'map': (arr, arg) => arr.map(v => v[arg]),
|
||||
'minus': bindFixed((v, arg) => v - arg),
|
||||
'modulo': bindFixed((v, arg) => v % arg),
|
||||
'newline_to_br': v => v.replace(/\n/g, '<br />'),
|
||||
'plus': bindFixed((v, arg) => v + arg),
|
||||
'prepend': (v, arg) => arg + v,
|
||||
'remove': (v, arg) => v.split(arg).join(''),
|
||||
'remove_first': (v, l) => v.replace(l, ''),
|
||||
'replace': (v, pattern, replacement) =>
|
||||
stringify(v).split(pattern).join(replacement),
|
||||
'replace_first': (v, arg1, arg2) => stringify(v).replace(arg1, arg2),
|
||||
'reverse': v => v.reverse(),
|
||||
'round': (v, arg) => {
|
||||
var amp = Math.pow(10, arg || 0);
|
||||
return Math.round(v * amp, arg) / amp;
|
||||
},
|
||||
'rstrip': str => stringify(str).replace(/\s+$/, ''),
|
||||
'size': v => v.length,
|
||||
'slice': (v, begin, length) =>
|
||||
v.substr(begin, length === undefined ? 1 : length),
|
||||
'sort': (v, arg) => v.sort(arg),
|
||||
'split': (v, arg) => stringify(v).split(arg),
|
||||
'strip': (v) => stringify(v).trim(),
|
||||
'strip_html': v => stringify(v).replace(/<\/?\s*\w+\s*\/?>/g, ''),
|
||||
'strip_newlines': v => stringify(v).replace(/\n/g, ''),
|
||||
'times': (v, arg) => v * arg,
|
||||
'truncate': (v, l, o) => {
|
||||
v = stringify(v);
|
||||
o = (o === undefined) ? '...' : o;
|
||||
l = l || 16;
|
||||
if (v.length <= l) return v;
|
||||
return v.substr(0, l - o.length) + o;
|
||||
},
|
||||
'truncatewords': (v, l, o) => {
|
||||
if (o === undefined) o = '...';
|
||||
var arr = v.split(' ');
|
||||
var ret = arr.slice(0, l).join(' ');
|
||||
if (arr.length > l) ret += o;
|
||||
return ret;
|
||||
},
|
||||
'uniq': function(arr) {
|
||||
var u = {};
|
||||
return (arr || []).filter(val => {
|
||||
if (u.hasOwnProperty(val)) {
|
||||
return false;
|
||||
}
|
||||
u[val] = true;
|
||||
return true;
|
||||
});
|
||||
},
|
||||
'upcase': str => stringify(str).toUpperCase(),
|
||||
'url_encode': encodeURIComponent
|
||||
};
|
||||
|
||||
function escape(str) {
|
||||
return stringify(str).replace(/&|<|>|"|'/g, m => escapeMap[m]);
|
||||
'escape_once': str => escape(unescape(str)),
|
||||
'first': v => v[0],
|
||||
'floor': v => Math.floor(v),
|
||||
'join': (v, arg) => v.join(arg),
|
||||
'last': v => v[v.length - 1],
|
||||
'lstrip': v => stringify(v).replace(/^\s+/, ''),
|
||||
'map': (arr, arg) => arr.map(v => v[arg]),
|
||||
'minus': bindFixed((v, arg) => v - arg),
|
||||
'modulo': bindFixed((v, arg) => v % arg),
|
||||
'newline_to_br': v => v.replace(/\n/g, '<br />'),
|
||||
'plus': bindFixed((v, arg) => Number(v) + Number(arg)),
|
||||
'prepend': (v, arg) => arg + v,
|
||||
'remove': (v, arg) => v.split(arg).join(''),
|
||||
'remove_first': (v, l) => v.replace(l, ''),
|
||||
'replace': (v, pattern, replacement) =>
|
||||
stringify(v).split(pattern).join(replacement),
|
||||
'replace_first': (v, arg1, arg2) => stringify(v).replace(arg1, arg2),
|
||||
'reverse': v => v.reverse(),
|
||||
'round': (v, arg) => {
|
||||
var amp = Math.pow(10, arg || 0)
|
||||
return Math.round(v * amp, arg) / amp
|
||||
},
|
||||
'rstrip': str => stringify(str).replace(/\s+$/, ''),
|
||||
'size': v => v.length,
|
||||
'slice': (v, begin, length) =>
|
||||
v.substr(begin, length === undefined ? 1 : length),
|
||||
'sort': (v, arg) => v.sort(arg),
|
||||
'split': (v, arg) => stringify(v).split(arg),
|
||||
'strip': (v) => stringify(v).trim(),
|
||||
'strip_html': v => stringify(v).replace(/<script.*?<\/script>|<!--.*?-->|<style.*?<\/style>|<.*?>/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))
|
||||
}
|
||||
|
||||
function isValidDate (date) {
|
||||
return date instanceof Date && !isNaN(date.getTime())
|
||||
}
|
||||
|
||||
registerAll.filters = filters
|
||||
module.exports = registerAll
|
||||
|
||||
@@ -1,152 +1,189 @@
|
||||
const Scope = require('./src/scope');
|
||||
const _ = require('./src/util/underscore.js');
|
||||
const assert = require('./src/util/assert.js');
|
||||
const tokenizer = require('./src/tokenizer.js');
|
||||
const statFileAsync = require('./src/util/fs.js').statFileAsync;
|
||||
const readFileAsync = require('./src/util/fs.js').readFileAsync;
|
||||
const path = require('path');
|
||||
const Render = require('./src/render.js');
|
||||
const lexical = require('./src/lexical.js');
|
||||
const Tag = require('./src/tag.js');
|
||||
const Filter = require('./src/filter.js');
|
||||
const Parser = require('./src/parser');
|
||||
const Syntax = require('./src/syntax.js');
|
||||
const tags = require('./tags');
|
||||
const filters = require('./filters');
|
||||
const Promise = require('any-promise');
|
||||
const anySeries = require('./src/util/promise.js').anySeries;
|
||||
const Errors = require('./src/util/error.js');
|
||||
const Scope = require('./src/scope')
|
||||
const _ = require('./src/util/underscore.js')
|
||||
const assert = require('./src/util/assert.js')
|
||||
const tokenizer = require('./src/tokenizer.js')
|
||||
const statFileAsync = require('./src/util/fs.js').statFileAsync
|
||||
const readFileAsync = require('./src/util/fs.js').readFileAsync
|
||||
const path = require('path')
|
||||
const url = require('./src/util/url.js')
|
||||
const Render = require('./src/render.js')
|
||||
const lexical = require('./src/lexical.js')
|
||||
const Tag = require('./src/tag.js')
|
||||
const Filter = require('./src/filter.js')
|
||||
const Parser = require('./src/parser')
|
||||
const Syntax = require('./src/syntax.js')
|
||||
const tags = require('./tags')
|
||||
const filters = require('./filters')
|
||||
const anySeries = require('./src/util/promise.js').anySeries
|
||||
const Errors = require('./src/util/error.js')
|
||||
|
||||
var _engine = {
|
||||
init: function(tag, filter, options) {
|
||||
if (options.cache) {
|
||||
this.cache = {};
|
||||
}
|
||||
this.options = options;
|
||||
this.tag = tag;
|
||||
this.filter = filter;
|
||||
this.parser = Parser(tag, filter);
|
||||
this.renderer = Render();
|
||||
|
||||
tags(this);
|
||||
filters(this);
|
||||
|
||||
return this;
|
||||
},
|
||||
parse: function(html) {
|
||||
var tokens = tokenizer.parse(html);
|
||||
return this.parser.parse(tokens);
|
||||
},
|
||||
render: function(tpl, ctx, opts) {
|
||||
opts = _.assign({}, this.options, opts);
|
||||
var scope = Scope.factory(ctx, opts);
|
||||
return this.renderer.renderTemplates(tpl, scope);
|
||||
},
|
||||
parseAndRender: function(html, ctx, opts) {
|
||||
return Promise.resolve()
|
||||
.then(() => this.parse(html))
|
||||
.then(tpl => this.render(tpl, ctx, opts))
|
||||
.catch(e => {
|
||||
if (e instanceof Errors.RenderBreakError) {
|
||||
return e.html;
|
||||
}
|
||||
throw e;
|
||||
});
|
||||
},
|
||||
renderFile: function(filepath, ctx, opts) {
|
||||
opts = _.assign({}, opts);
|
||||
return this.getTemplate(filepath, opts.root)
|
||||
.then(templates => this.render(templates, ctx, opts))
|
||||
.catch(e => {
|
||||
e.file = filepath;
|
||||
throw e;
|
||||
});
|
||||
},
|
||||
evalOutput: function(str, scope) {
|
||||
var tpl = this.parser.parseOutput(str.trim());
|
||||
return this.renderer.evalOutput(tpl, scope);
|
||||
},
|
||||
registerFilter: function(name, filter) {
|
||||
return this.filter.register(name, filter);
|
||||
},
|
||||
registerTag: function(name, tag) {
|
||||
return this.tag.register(name, tag);
|
||||
},
|
||||
lookup: function(filepath, root) {
|
||||
root = this.options.root.concat(root || []);
|
||||
root = _.uniq(root);
|
||||
var paths = root.map(root => path.resolve(root, filepath));
|
||||
return anySeries(paths, path => statFileAsync(path).then(() => path))
|
||||
.catch((e) => {
|
||||
if (e.code === 'ENOENT') {
|
||||
e.message = `Failed to lookup ${filepath} in: ${root}`;
|
||||
}
|
||||
throw e;
|
||||
});
|
||||
},
|
||||
getTemplate: function(filepath, root) {
|
||||
if(!path.extname(filepath)){
|
||||
filepath += this.options.extname;
|
||||
}
|
||||
return this
|
||||
.lookup(filepath, root)
|
||||
.then(filepath => {
|
||||
if (this.options.cache) {
|
||||
var tpl = this.cache[filepath];
|
||||
if (tpl) {
|
||||
return Promise.resolve(tpl);
|
||||
}
|
||||
return readFileAsync(filepath)
|
||||
.then(str => this.parse(str))
|
||||
.then(tpl => this.cache[filepath] = tpl);
|
||||
} else {
|
||||
return readFileAsync(filepath).then(str => this.parse(str));
|
||||
}
|
||||
});
|
||||
},
|
||||
express: function(opts) {
|
||||
opts = opts || {};
|
||||
var self = this;
|
||||
return function(filePath, ctx, callback) {
|
||||
assert(_.isArray(this.root) || _.isString(this.root),
|
||||
'illegal views root, are you using express.js?');
|
||||
opts.root = this.root;
|
||||
self.renderFile(filePath, ctx, opts)
|
||||
.then(html => callback(null, html))
|
||||
.catch(e => callback(e));
|
||||
};
|
||||
init: function (tag, filter, options) {
|
||||
if (options.cache) {
|
||||
this.cache = {}
|
||||
}
|
||||
};
|
||||
this.options = options
|
||||
this.tag = tag
|
||||
this.filter = filter
|
||||
this.parser = Parser(tag, filter)
|
||||
this.renderer = Render()
|
||||
|
||||
function factory(options) {
|
||||
options = _.assign({}, options);
|
||||
options.root = normalizeStringArray(options.root);
|
||||
if (!options.root.length) options.root = ['.'];
|
||||
tags(this)
|
||||
filters(this)
|
||||
|
||||
options.extname = options.extname || '.liquid';
|
||||
|
||||
var engine = Object.create(_engine);
|
||||
|
||||
engine.init(Tag(), Filter(options), options);
|
||||
return engine;
|
||||
return this
|
||||
},
|
||||
parse: function (html, filepath) {
|
||||
var tokens = tokenizer.parse(html, filepath, this.options)
|
||||
return this.parser.parse(tokens)
|
||||
},
|
||||
render: function (tpl, ctx, opts) {
|
||||
opts = _.assign({}, this.options, opts)
|
||||
var scope = Scope.factory(ctx, opts)
|
||||
return this.renderer.renderTemplates(tpl, scope)
|
||||
},
|
||||
parseAndRender: function (html, ctx, opts) {
|
||||
return Promise.resolve()
|
||||
.then(() => this.parse(html))
|
||||
.then(tpl => this.render(tpl, ctx, opts))
|
||||
},
|
||||
renderFile: function (filepath, ctx, opts) {
|
||||
opts = _.assign({}, opts)
|
||||
return this.getTemplate(filepath, opts.root)
|
||||
.then(templates => this.render(templates, ctx, opts))
|
||||
},
|
||||
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)
|
||||
},
|
||||
registerTag: function (name, tag) {
|
||||
return this.tag.register(name, tag)
|
||||
},
|
||||
lookup: function (filepath, root) {
|
||||
root = this.options.root.concat(root || [])
|
||||
root = _.uniq(root)
|
||||
var paths = root.map(root => path.resolve(root, filepath))
|
||||
return anySeries(paths, path => statFileAsync(path).then(() => path))
|
||||
.catch((e) => {
|
||||
e.message = `${e.code}: Failed to lookup ${filepath} in: ${root}`
|
||||
throw e
|
||||
})
|
||||
},
|
||||
getTemplate: function (filepath, root) {
|
||||
return typeof XMLHttpRequest === 'undefined'
|
||||
? this.getTemplateFromFile(filepath, root)
|
||||
: this.getTemplateFromUrl(filepath, root)
|
||||
},
|
||||
getTemplateFromFile: function (filepath, root) {
|
||||
if (!path.extname(filepath)) {
|
||||
filepath += this.options.extname
|
||||
}
|
||||
return this
|
||||
.lookup(filepath, root)
|
||||
.then(filepath => {
|
||||
if (this.options.cache) {
|
||||
var tpl = this.cache[filepath]
|
||||
if (tpl) {
|
||||
return Promise.resolve(tpl)
|
||||
}
|
||||
return readFileAsync(filepath)
|
||||
.then(str => this.parse(str))
|
||||
.then(tpl => (this.cache[filepath] = tpl))
|
||||
} else {
|
||||
return readFileAsync(filepath).then(str => this.parse(str, filepath))
|
||||
}
|
||||
})
|
||||
},
|
||||
getTemplateFromUrl: function (filepath, root) {
|
||||
var fullUrl
|
||||
if (url.valid(filepath)) {
|
||||
fullUrl = filepath
|
||||
} else {
|
||||
if (!url.extname(filepath)) {
|
||||
filepath += this.options.extname
|
||||
}
|
||||
fullUrl = url.resolve(root || this.options.root, filepath)
|
||||
}
|
||||
if (this.options.cache) {
|
||||
var tpl = this.cache[filepath]
|
||||
if (tpl) {
|
||||
return Promise.resolve(tpl)
|
||||
}
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
var xhr = new XMLHttpRequest()
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
var tpl = this.parse(xhr.responseText)
|
||||
if (this.options.cache) {
|
||||
this.cache[filepath] = tpl
|
||||
}
|
||||
resolve(tpl)
|
||||
} else {
|
||||
reject(new Error(xhr.statusText))
|
||||
}
|
||||
}
|
||||
xhr.onerror = () => {
|
||||
reject(new Error('An error occurred whilst sending the response.'))
|
||||
}
|
||||
xhr.open('GET', fullUrl)
|
||||
xhr.send()
|
||||
})
|
||||
},
|
||||
express: function (opts) {
|
||||
opts = opts || {}
|
||||
var self = this
|
||||
return function (filePath, ctx, callback) {
|
||||
assert(Array.isArray(this.root) || _.isString(this.root),
|
||||
'illegal views root, are you using express.js?')
|
||||
opts.root = this.root
|
||||
self.renderFile(filePath, ctx, opts)
|
||||
.then(html => callback(null, html))
|
||||
.catch(e => callback(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeStringArray(value) {
|
||||
if (_.isArray(value)) return value;
|
||||
if (_.isString(value)) return [value];
|
||||
return [];
|
||||
function factory (options) {
|
||||
options = _.assign({
|
||||
root: ['.'],
|
||||
cache: false,
|
||||
extname: '',
|
||||
dynamicPartials: true,
|
||||
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)
|
||||
options.root = normalizeStringArray(options.root)
|
||||
|
||||
var engine = Object.create(_engine)
|
||||
engine.init(Tag(), Filter(options), options)
|
||||
return engine
|
||||
}
|
||||
|
||||
factory.lexical = lexical;
|
||||
factory.isTruthy = Syntax.isTruthy;
|
||||
factory.isFalsy = Syntax.isFalsy;
|
||||
factory.evalExp = Syntax.evalExp;
|
||||
factory.evalValue = Syntax.evalValue;
|
||||
function normalizeStringArray (value) {
|
||||
if (Array.isArray(value)) return value
|
||||
if (_.isString(value)) return [value]
|
||||
return []
|
||||
}
|
||||
|
||||
factory.lexical = lexical
|
||||
factory.isTruthy = Syntax.isTruthy
|
||||
factory.isFalsy = Syntax.isFalsy
|
||||
factory.evalExp = Syntax.evalExp
|
||||
factory.evalValue = Syntax.evalValue
|
||||
factory.Types = {
|
||||
ParseError: Errors.ParseError,
|
||||
TokenizationEroor: Errors.TokenizationError,
|
||||
RenderBreakError: Errors.RenderBreakError,
|
||||
AssertionError: Errors.AssertionError
|
||||
};
|
||||
ParseError: Errors.ParseError,
|
||||
TokenizationEroor: Errors.TokenizationError,
|
||||
RenderBreakError: Errors.RenderBreakError,
|
||||
AssertionError: Errors.AssertionError
|
||||
}
|
||||
|
||||
module.exports = factory;
|
||||
module.exports = factory
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
MINIFY = ./node_modules/.bin/uglifyjs
|
||||
BROWSERIFY = ./node_modules/.bin/browserify
|
||||
|
||||
.PHONY: dist default clean
|
||||
|
||||
default:
|
||||
|
||||
dist:
|
||||
[ -d dist/ ] || mkdir dist/
|
||||
$(BROWSERIFY) index.js -s Liquid \
|
||||
--ignore path \
|
||||
-t [ babelify --global true --presets [ es2015 ] ] \
|
||||
> dist/liquid.js
|
||||
$(MINIFY) dist/liquid.js --compress warnings=false --mangle --output dist/liquid.min.js
|
||||
ls -lh dist/
|
||||
|
||||
clean:
|
||||
rm -rf dist/
|
||||
+46
-24
@@ -1,48 +1,70 @@
|
||||
{
|
||||
"name": "shopify-liquid",
|
||||
"version": "1.4.1",
|
||||
"description": "Liquid template engine for JavaScript, Node.js and Browser",
|
||||
"name": "liquidjs",
|
||||
"version": "5.0.1",
|
||||
"description": "Liquid template engine by pure JavaScript: compatible to shopify, easy to extend.",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "mocha --recursive",
|
||||
"dist": "make dist",
|
||||
"preversion": "npm test",
|
||||
"coverage": "cross-env NODE_ENV=test istanbul cover --report html ./node_modules/mocha/bin/_mocha -- -R spec --recursive",
|
||||
"lcov": "cross-env NODE_ENV=test istanbul cover --report lcovonly ./node_modules/mocha/bin/_mocha -- -R spec --recursive",
|
||||
"dist": "npm run browserify && npm run uglify",
|
||||
"browserify": "browserify index.js -s Liquid --ignore path -t [ babelify --global true --presets [ es2015 ] ] > dist/liquid.js",
|
||||
"uglify": "uglifyjs dist/liquid.js --compress warnings=false --mangle --output dist/liquid.min.js",
|
||||
"preversion": "npm run lint && npm test",
|
||||
"version": "npm run dist && git add -A dist",
|
||||
"postversion": "git push && git push --tags"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/harttle/shopify-liquid.git"
|
||||
"url": "git+https://github.com/harttle/liquidjs.git"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4.8.7"
|
||||
},
|
||||
"keywords": [
|
||||
"liquid",
|
||||
"template",
|
||||
"template engine",
|
||||
"express",
|
||||
"jinja",
|
||||
"shopify"
|
||||
],
|
||||
"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"
|
||||
"resolve-url": "^0.2.1"
|
||||
},
|
||||
"browser": {
|
||||
"fs": false
|
||||
},
|
||||
"devDependencies": {
|
||||
"babel-preset-es2015": "^6.14.0",
|
||||
"babelify": "^7.3.0",
|
||||
"browserify": "^13.1.0",
|
||||
"chai": "^3.5.0",
|
||||
"chai-as-promised": "^5.3.0",
|
||||
"coveralls": "^2.11.9",
|
||||
"express": "^4.14.0",
|
||||
"istanbul": "^0.4.3",
|
||||
"mocha": "^3.0.2",
|
||||
"mock-fs": "^3.9.0",
|
||||
"sinon": "^1.17.4",
|
||||
"sinon-chai": "^2.8.0",
|
||||
"supertest": "^2.0.0",
|
||||
"uglifyjs": "^2.4.10"
|
||||
"babel-core": "^6.26.0",
|
||||
"babel-preset-es2015": "^6.24.1",
|
||||
"babelify": "^8.0.0",
|
||||
"browserify": "^14.4.0",
|
||||
"chai": "^4.1.2",
|
||||
"chai-as-promised": "^7.1.1",
|
||||
"coveralls": "^3.0.0",
|
||||
"cross-env": "^5.1.3",
|
||||
"eslint": "^4.8.0",
|
||||
"eslint-config-standard": "^10.2.1",
|
||||
"eslint-plugin-import": "^2.7.0",
|
||||
"eslint-plugin-mocha": "^4.11.0",
|
||||
"eslint-plugin-node": "^5.2.0",
|
||||
"eslint-plugin-promise": "^3.5.0",
|
||||
"eslint-plugin-standard": "^3.0.1",
|
||||
"express": "^4.16.1",
|
||||
"istanbul": "^0.4.5",
|
||||
"jsdom": "^11.5.1",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
||||
+58
-56
@@ -1,66 +1,68 @@
|
||||
const lexical = require('./lexical.js');
|
||||
const Syntax = require('./syntax.js');
|
||||
const assert = require('./util/assert.js');
|
||||
const _ = require('./util/underscore.js');
|
||||
const lexical = require('./lexical.js')
|
||||
const Syntax = require('./syntax.js')
|
||||
const assert = require('./util/assert.js')
|
||||
const _ = require('./util/underscore.js')
|
||||
|
||||
var valueRE = new RegExp(`${lexical.value.source}`, 'g');
|
||||
var valueRE = new RegExp(`${lexical.value.source}`, 'g')
|
||||
|
||||
module.exports = function(options) {
|
||||
options = _.assign({}, options);
|
||||
var filters = {};
|
||||
module.exports = function (options) {
|
||||
options = _.assign({}, options)
|
||||
var filters = {}
|
||||
|
||||
var _filterInstance = {
|
||||
render: function(output, scope) {
|
||||
var args = this.args.map(arg => Syntax.evalValue(arg, scope));
|
||||
args.unshift(output);
|
||||
return this.filter.apply(null, args);
|
||||
},
|
||||
parse: function(str) {
|
||||
var match = lexical.filterLine.exec(str);
|
||||
assert(match, 'illegal filter: ' + str);
|
||||
var _filterInstance = {
|
||||
render: function (output, scope) {
|
||||
var args = this.args.map(arg => Syntax.evalValue(arg, scope))
|
||||
args.unshift(output)
|
||||
return this.filter.apply(null, args)
|
||||
},
|
||||
parse: function (str) {
|
||||
var match = lexical.filterLine.exec(str)
|
||||
assert(match, 'illegal filter: ' + str)
|
||||
|
||||
var name = match[1], argList = match[2] || '', filter = filters[name];
|
||||
if (typeof filter !== 'function'){
|
||||
if(options.strict_filters){
|
||||
throw new TypeError(`undefined filter: ${name}`);
|
||||
}
|
||||
this.name= name;
|
||||
this.filter= x => x;
|
||||
this.args= [];
|
||||
return this;
|
||||
//return {
|
||||
//name: name,
|
||||
//error: new TypeError(`undefined filter: ${name}`)
|
||||
//};
|
||||
}
|
||||
|
||||
var args = [];
|
||||
while(match = valueRE.exec(argList.trim())){
|
||||
args.push(match[0]);
|
||||
}
|
||||
|
||||
this.name = name;
|
||||
this.filter = filter;
|
||||
this.args = args;
|
||||
|
||||
return this;
|
||||
var name = match[1]
|
||||
var argList = match[2] || ''
|
||||
var filter = filters[name]
|
||||
if (typeof filter !== 'function') {
|
||||
if (options.strict_filters) {
|
||||
throw new TypeError(`undefined filter: ${name}`)
|
||||
}
|
||||
};
|
||||
this.name = name
|
||||
this.filter = x => x
|
||||
this.args = []
|
||||
return this
|
||||
}
|
||||
|
||||
function construct(str) {
|
||||
var instance = Object.create(_filterInstance);
|
||||
return instance.parse(str);
|
||||
var args = []
|
||||
while ((match = valueRE.exec(argList.trim()))) {
|
||||
var v = match[0]
|
||||
var re = new RegExp(`${v}\\s*:`, 'g')
|
||||
var keyMatch = re.exec(match.input)
|
||||
var currentMatchIsKey = keyMatch && keyMatch.index === match.index
|
||||
currentMatchIsKey ? args.push(`'${v}'`) : args.push(v)
|
||||
}
|
||||
|
||||
this.name = name
|
||||
this.filter = filter
|
||||
this.args = args
|
||||
|
||||
return this
|
||||
}
|
||||
}
|
||||
|
||||
function register(name, filter) {
|
||||
filters[name] = filter;
|
||||
}
|
||||
function construct (str) {
|
||||
var instance = Object.create(_filterInstance)
|
||||
return instance.parse(str)
|
||||
}
|
||||
|
||||
function clear() {
|
||||
filters = {};
|
||||
}
|
||||
function register (name, filter) {
|
||||
filters[name] = filter
|
||||
}
|
||||
|
||||
return {
|
||||
construct, register, clear
|
||||
};
|
||||
};
|
||||
function clear () {
|
||||
filters = {}
|
||||
}
|
||||
|
||||
return {
|
||||
construct, register, clear
|
||||
}
|
||||
}
|
||||
|
||||
+86
-61
@@ -1,91 +1,116 @@
|
||||
// quote related
|
||||
var singleQuoted = /'[^']*'/;
|
||||
var doubleQuoted = /"[^"]*"/;
|
||||
var quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`);
|
||||
var quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`);
|
||||
var singleQuoted = /'[^']*'/
|
||||
var doubleQuoted = /"[^"]*"/
|
||||
var quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
|
||||
var quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`)
|
||||
|
||||
// basic types
|
||||
var integer = /-?\d+/;
|
||||
var number = /-?\d+\.?\d*|\.?\d+/;
|
||||
var bool = /true|false/;
|
||||
var integer = /-?\d+/
|
||||
var number = /-?\d+\.?\d*|\.?\d+/
|
||||
var bool = /true|false/
|
||||
|
||||
// peoperty access
|
||||
var identifier = /[\w-]+/;
|
||||
var subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`);
|
||||
var literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`);
|
||||
var variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`);
|
||||
var identifier = /[\w-]+/
|
||||
var subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`)
|
||||
var literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`)
|
||||
var variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`)
|
||||
|
||||
// range related
|
||||
var rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`);
|
||||
var range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`);
|
||||
var rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`);
|
||||
var rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`)
|
||||
var range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`)
|
||||
var rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`)
|
||||
|
||||
var value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`);
|
||||
var value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
|
||||
|
||||
// hash related
|
||||
var hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`);
|
||||
var hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g');
|
||||
var hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`)
|
||||
var hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
|
||||
|
||||
// full match
|
||||
var tagLine = new RegExp(`^\\s*(${identifier.source})\\s*(.*)\\s*$`);
|
||||
var literalLine = new RegExp(`^${literal.source}$`, 'i');
|
||||
var variableLine = new RegExp(`^${variable.source}$`);
|
||||
var numberLine = new RegExp(`^${number.source}$`);
|
||||
var boolLine = new RegExp(`^${bool.source}$`, 'i');
|
||||
var quotedLine = new RegExp(`^${quoted.source}$`);
|
||||
var rangeLine = new RegExp(`^${rangeCapture.source}$`);
|
||||
var integerLine = new RegExp(`^${integer.source}$`);
|
||||
var tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`)
|
||||
var literalLine = new RegExp(`^${literal.source}$`, 'i')
|
||||
var variableLine = new RegExp(`^${variable.source}$`)
|
||||
var numberLine = new RegExp(`^${number.source}$`)
|
||||
var boolLine = new RegExp(`^${bool.source}$`, 'i')
|
||||
var quotedLine = new RegExp(`^${quoted.source}$`)
|
||||
var rangeLine = new RegExp(`^${rangeCapture.source}$`)
|
||||
var integerLine = new RegExp(`^${integer.source}$`)
|
||||
|
||||
// filter related
|
||||
var valueList = new RegExp(`${value.source}(\\s*,\\s*${value.source})*`);
|
||||
var filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g');
|
||||
var filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`);
|
||||
var filterLine = new RegExp(`^${filterCapture.source}$`);
|
||||
var valueDeclaration = new RegExp(`(?:${identifier.source}\\s*:\\s*)?${value.source}`)
|
||||
var valueList = new RegExp(`${valueDeclaration.source}(\\s*,\\s*${valueDeclaration.source})*`)
|
||||
var filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g')
|
||||
var filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`)
|
||||
var filterLine = new RegExp(`^${filterCapture.source}$`)
|
||||
|
||||
var operators = [
|
||||
/\s+or\s+/,
|
||||
/\s+and\s+/,
|
||||
/==|!=|<=|>=|<|>|\s+contains\s+/
|
||||
];
|
||||
/\s+or\s+/,
|
||||
/\s+and\s+/,
|
||||
/==|!=|<=|>=|<|>|\s+contains\s+/
|
||||
]
|
||||
|
||||
function isInteger(str){
|
||||
return integerLine.test(str);
|
||||
function isInteger (str) {
|
||||
return integerLine.test(str)
|
||||
}
|
||||
|
||||
function isLiteral(str) {
|
||||
return literalLine.test(str);
|
||||
function isLiteral (str) {
|
||||
return literalLine.test(str)
|
||||
}
|
||||
|
||||
function isRange(str) {
|
||||
return rangeLine.test(str);
|
||||
function isRange (str) {
|
||||
return rangeLine.test(str)
|
||||
}
|
||||
|
||||
function isVariable(str) {
|
||||
return variableLine.test(str);
|
||||
function isVariable (str) {
|
||||
return variableLine.test(str)
|
||||
}
|
||||
|
||||
function matchValue(str) {
|
||||
return value.exec(str);
|
||||
function matchValue (str) {
|
||||
return value.exec(str)
|
||||
}
|
||||
|
||||
function parseLiteral(str) {
|
||||
var res;
|
||||
if (res = str.match(numberLine)) {
|
||||
return Number(str);
|
||||
}
|
||||
if (res = str.match(boolLine)) {
|
||||
return str.toLowerCase() === 'true';
|
||||
}
|
||||
if (res = str.match(quotedLine)) {
|
||||
return str.slice(1, -1);
|
||||
}
|
||||
function parseLiteral (str) {
|
||||
var res = str.match(numberLine)
|
||||
if (res) {
|
||||
return Number(str)
|
||||
}
|
||||
res = str.match(boolLine)
|
||||
if (res) {
|
||||
return str.toLowerCase() === 'true'
|
||||
}
|
||||
res = str.match(quotedLine)
|
||||
if (res) {
|
||||
return str.slice(1, -1)
|
||||
}
|
||||
throw new TypeError(`cannot parse '${str}' as literal`)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
quoted, number, bool, literal, filter, integer,
|
||||
hash, hashCapture,
|
||||
range, rangeCapture,
|
||||
identifier, value, quoteBalanced, operators,
|
||||
quotedLine, numberLine, boolLine, rangeLine, literalLine, filterLine, tagLine,
|
||||
isLiteral, isVariable, parseLiteral, isRange, matchValue, isInteger
|
||||
};
|
||||
quoted,
|
||||
number,
|
||||
bool,
|
||||
literal,
|
||||
filter,
|
||||
integer,
|
||||
hash,
|
||||
hashCapture,
|
||||
range,
|
||||
rangeCapture,
|
||||
identifier,
|
||||
value,
|
||||
quoteBalanced,
|
||||
operators,
|
||||
quotedLine,
|
||||
numberLine,
|
||||
boolLine,
|
||||
rangeLine,
|
||||
literalLine,
|
||||
filterLine,
|
||||
tagLine,
|
||||
isLiteral,
|
||||
isVariable,
|
||||
parseLiteral,
|
||||
isRange,
|
||||
matchValue,
|
||||
isInteger
|
||||
}
|
||||
|
||||
+17
-13
@@ -1,13 +1,17 @@
|
||||
var operators = {
|
||||
'==': (l, r) => l == r,
|
||||
'!=': (l, r) => l != r,
|
||||
'>': (l, r) => l > r,
|
||||
'<': (l, r) => l < r,
|
||||
'>=': (l, r) => l >= r,
|
||||
'<=': (l, r) => l <= r,
|
||||
'contains': (l, r) => l.indexOf(r) > -1,
|
||||
'and': (l, r) => l && r,
|
||||
'or': (l, r) => l || r
|
||||
};
|
||||
|
||||
module.exports = operators;
|
||||
module.exports = function (isTruthy) {
|
||||
return {
|
||||
'==': (l, r) => l === r,
|
||||
'!=': (l, r) => l !== r,
|
||||
'>': (l, r) => l !== null && r !== null && l > r,
|
||||
'<': (l, r) => l !== null && r !== null && l < r,
|
||||
'>=': (l, r) => l !== null && r !== null && l >= r,
|
||||
'<=': (l, r) => l !== null && r !== null && l <= r,
|
||||
'contains': (l, r) => {
|
||||
if (!l) return false
|
||||
if (typeof l.indexOf !== 'function') return false
|
||||
return l.indexOf(r) > -1
|
||||
},
|
||||
'and': (l, r) => isTruthy(l) && isTruthy(r),
|
||||
'or': (l, r) => isTruthy(l) || isTruthy(r)
|
||||
}
|
||||
}
|
||||
|
||||
+91
-91
@@ -1,105 +1,105 @@
|
||||
const lexical = require('./lexical.js');
|
||||
const ParseError = require('./util/error.js').ParseError;
|
||||
const assert = require('./util/assert.js');
|
||||
const lexical = require('./lexical.js')
|
||||
const ParseError = require('./util/error.js').ParseError
|
||||
const assert = require('./util/assert.js')
|
||||
|
||||
module.exports = function(Tag, Filter) {
|
||||
|
||||
var stream = {
|
||||
init: function(tokens) {
|
||||
this.tokens = tokens;
|
||||
this.handlers = {};
|
||||
return this;
|
||||
},
|
||||
on: function(name, cb) {
|
||||
this.handlers[name] = cb;
|
||||
return this;
|
||||
},
|
||||
trigger: function(event, arg) {
|
||||
var h = this.handlers[event];
|
||||
if (typeof h === 'function') {
|
||||
h(arg);
|
||||
return true;
|
||||
}
|
||||
},
|
||||
start: function() {
|
||||
this.trigger('start');
|
||||
var token;
|
||||
while (!this.stopRequested && (token = this.tokens.shift())) {
|
||||
if (this.trigger('token', token)) continue;
|
||||
if (token.type == 'tag' &&
|
||||
this.trigger(`tag:${token.name}`, token)) {
|
||||
continue;
|
||||
}
|
||||
var template = parseToken(token, this.tokens);
|
||||
this.trigger('template', template);
|
||||
}
|
||||
if (!this.stopRequested) this.trigger('end');
|
||||
return this;
|
||||
},
|
||||
stop: function() {
|
||||
this.stopRequested = true;
|
||||
return this;
|
||||
module.exports = function (Tag, Filter) {
|
||||
var stream = {
|
||||
init: function (tokens) {
|
||||
this.tokens = tokens
|
||||
this.handlers = {}
|
||||
return this
|
||||
},
|
||||
on: function (name, cb) {
|
||||
this.handlers[name] = cb
|
||||
return this
|
||||
},
|
||||
trigger: function (event, arg) {
|
||||
var h = this.handlers[event]
|
||||
if (typeof h === 'function') {
|
||||
h(arg)
|
||||
return true
|
||||
}
|
||||
},
|
||||
start: function () {
|
||||
this.trigger('start')
|
||||
var token
|
||||
while (!this.stopRequested && (token = this.tokens.shift())) {
|
||||
if (this.trigger('token', token)) continue
|
||||
if (token.type === 'tag' &&
|
||||
this.trigger(`tag:${token.name}`, token)) {
|
||||
continue
|
||||
}
|
||||
};
|
||||
|
||||
function parse(tokens) {
|
||||
var token, templates = [];
|
||||
while (token = tokens.shift()) {
|
||||
templates.push(parseToken(token, tokens));
|
||||
}
|
||||
return templates;
|
||||
var template = parseToken(token, this.tokens)
|
||||
this.trigger('template', template)
|
||||
}
|
||||
if (!this.stopRequested) this.trigger('end')
|
||||
return this
|
||||
},
|
||||
stop: function () {
|
||||
this.stopRequested = true
|
||||
return this
|
||||
}
|
||||
}
|
||||
|
||||
function parseToken(token, tokens) {
|
||||
try {
|
||||
var tpl = null;
|
||||
if (token.type === 'tag') {
|
||||
tpl = parseTag(token, tokens);
|
||||
} else if (token.type === 'output') {
|
||||
tpl = parseOutput(token.value);
|
||||
} else { // token.type === 'html'
|
||||
tpl = token;
|
||||
}
|
||||
tpl.token = token;
|
||||
return tpl;
|
||||
} catch (e) {
|
||||
throw new ParseError(e, token);
|
||||
}
|
||||
function parse (tokens) {
|
||||
var token
|
||||
var templates = []
|
||||
while ((token = tokens.shift())) {
|
||||
templates.push(parseToken(token, tokens))
|
||||
}
|
||||
return templates
|
||||
}
|
||||
|
||||
function parseTag(token, tokens) {
|
||||
if (token.name === 'continue' || token.name === 'break') return token;
|
||||
return Tag.construct(token, tokens);
|
||||
function parseToken (token, tokens) {
|
||||
try {
|
||||
var tpl = null
|
||||
if (token.type === 'tag') {
|
||||
tpl = parseTag(token, tokens)
|
||||
} else if (token.type === 'value') {
|
||||
tpl = parseValue(token.value)
|
||||
} else { // token.type === 'html'
|
||||
tpl = token
|
||||
}
|
||||
tpl.token = token
|
||||
return tpl
|
||||
} catch (e) {
|
||||
throw new ParseError(e, token)
|
||||
}
|
||||
}
|
||||
|
||||
function parseOutput(str) {
|
||||
var match = lexical.matchValue(str);
|
||||
assert(match, `illegal output string: ${str}`);
|
||||
function parseTag (token, tokens) {
|
||||
if (token.name === 'continue' || token.name === 'break') return token
|
||||
return Tag.construct(token, tokens)
|
||||
}
|
||||
|
||||
var initial = match[0];
|
||||
str = str.substr(match.index + match[0].length);
|
||||
function parseValue (str) {
|
||||
var match = lexical.matchValue(str)
|
||||
assert(match, `illegal value string: ${str}`)
|
||||
|
||||
var filters = [];
|
||||
while (match = lexical.filter.exec(str)) {
|
||||
filters.push([match[0].trim()]);
|
||||
}
|
||||
var initial = match[0]
|
||||
str = str.substr(match.index + match[0].length)
|
||||
|
||||
return {
|
||||
type: 'output',
|
||||
initial: initial,
|
||||
filters: filters.map(str => Filter.construct(str))
|
||||
};
|
||||
}
|
||||
|
||||
function parseStream(tokens) {
|
||||
var s = Object.create(stream);
|
||||
return s.init(tokens);
|
||||
var filters = []
|
||||
while ((match = lexical.filter.exec(str))) {
|
||||
filters.push([match[0].trim()])
|
||||
}
|
||||
|
||||
return {
|
||||
parse,
|
||||
parseTag,
|
||||
parseStream,
|
||||
parseOutput
|
||||
};
|
||||
};
|
||||
type: 'value',
|
||||
initial: initial,
|
||||
filters: filters.map(str => Filter.construct(str))
|
||||
}
|
||||
}
|
||||
|
||||
function parseStream (tokens) {
|
||||
var s = Object.create(stream)
|
||||
return s.init(tokens)
|
||||
}
|
||||
|
||||
return {
|
||||
parse,
|
||||
parseTag,
|
||||
parseStream,
|
||||
parseValue
|
||||
}
|
||||
}
|
||||
|
||||
+56
-57
@@ -1,68 +1,67 @@
|
||||
const Syntax = require('./syntax.js');
|
||||
const Promise = require('any-promise');
|
||||
const mapSeries = require('./util/promise.js').mapSeries;
|
||||
const RenderBreakError = require('./util/error.js').RenderBreakError;
|
||||
const RenderError = require('./util/error.js').RenderError;
|
||||
const assert = require('./util/assert.js');
|
||||
const Syntax = require('./syntax.js')
|
||||
const mapSeries = require('./util/promise.js').mapSeries
|
||||
const RenderBreakError = require('./util/error.js').RenderBreakError
|
||||
const RenderError = require('./util/error.js').RenderError
|
||||
const assert = require('./util/assert.js')
|
||||
|
||||
var render = {
|
||||
|
||||
renderTemplates: function(templates, scope) {
|
||||
assert(scope, 'unable to evalTemplates: scope undefined');
|
||||
renderTemplates: function (templates, scope) {
|
||||
assert(scope, 'unable to evalTemplates: scope undefined')
|
||||
|
||||
var html = '';
|
||||
return mapSeries(templates, (tpl) => {
|
||||
return renderTemplate.call(this, tpl)
|
||||
.then(partial => html += partial)
|
||||
.catch(e => {
|
||||
if (e instanceof RenderBreakError) {
|
||||
e.resolvedHTML = html;
|
||||
throw e;
|
||||
}
|
||||
throw new RenderError(e, tpl);
|
||||
});
|
||||
}).then(() => html);
|
||||
var html = ''
|
||||
return mapSeries(templates, (tpl) => {
|
||||
return renderTemplate.call(this, tpl)
|
||||
.then(partial => (html += partial))
|
||||
.catch(e => {
|
||||
if (e instanceof RenderBreakError) {
|
||||
e.resolvedHTML = html
|
||||
throw e
|
||||
}
|
||||
throw new RenderError(e, tpl)
|
||||
})
|
||||
}).then(() => html)
|
||||
|
||||
function renderTemplate(template) {
|
||||
if (template.type === 'tag') {
|
||||
return this.renderTag(template, scope)
|
||||
.then(partial => partial === undefined ? '' : partial);
|
||||
} else if (template.type === 'output') {
|
||||
return Promise.resolve()
|
||||
.then(() => this.evalOutput(template, scope))
|
||||
.then(partial => partial === undefined ? '' : stringify(partial));
|
||||
} else { // template.type === 'html'
|
||||
return Promise.resolve(template.value);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
renderTag: function(template, scope) {
|
||||
if (template.name === 'continue') {
|
||||
return Promise.reject(new RenderBreakError('continue'));
|
||||
}
|
||||
if (template.name === 'break') {
|
||||
return Promise.reject(new RenderBreakError('break'));
|
||||
}
|
||||
return template.render(scope);
|
||||
},
|
||||
|
||||
evalOutput: function(template, scope) {
|
||||
assert(scope, 'unable to evalOutput: scope undefined');
|
||||
return template.filters.reduce(
|
||||
(prev, filter) => filter.render(prev, scope),
|
||||
Syntax.evalExp(template.initial, scope));
|
||||
function renderTemplate (template) {
|
||||
if (template.type === 'tag') {
|
||||
return this.renderTag(template, scope)
|
||||
.then(partial => partial === undefined ? '' : partial)
|
||||
} else if (template.type === 'value') {
|
||||
return Promise.resolve()
|
||||
.then(() => this.evalValue(template, scope))
|
||||
.then(partial => partial === undefined ? '' : stringify(partial))
|
||||
} else { // template.type === 'html'
|
||||
return Promise.resolve(template.value)
|
||||
}
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
function factory() {
|
||||
var instance = Object.create(render);
|
||||
return instance;
|
||||
renderTag: function (template, scope) {
|
||||
if (template.name === 'continue') {
|
||||
return Promise.reject(new RenderBreakError('continue'))
|
||||
}
|
||||
if (template.name === 'break') {
|
||||
return Promise.reject(new RenderBreakError('break'))
|
||||
}
|
||||
return template.render(scope)
|
||||
},
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
function stringify(val) {
|
||||
if (typeof val === 'string') return val;
|
||||
return JSON.stringify(val);
|
||||
function factory () {
|
||||
var instance = Object.create(render)
|
||||
return instance
|
||||
}
|
||||
|
||||
module.exports = factory;
|
||||
function stringify (val) {
|
||||
if (typeof val === 'string') return val
|
||||
return JSON.stringify(val)
|
||||
}
|
||||
|
||||
module.exports = factory
|
||||
|
||||
+183
-164
@@ -1,172 +1,191 @@
|
||||
const _ = require('./util/underscore.js');
|
||||
const lexical = require('./lexical.js');
|
||||
const assert = require('./util/assert.js');
|
||||
const _ = require('./util/underscore.js')
|
||||
const lexical = require('./lexical.js')
|
||||
const assert = require('./util/assert.js')
|
||||
|
||||
var Scope = {
|
||||
getAll: function() {
|
||||
var ctx = {};
|
||||
for (var i = this.scopes.length - 1; i >= 0; i--) {
|
||||
_.assign(ctx, this.scopes[i]);
|
||||
}
|
||||
return ctx;
|
||||
},
|
||||
get: function(str) {
|
||||
for (var i = this.scopes.length - 1; i >= 0; i--) {
|
||||
try {
|
||||
return this.getPropertyByPath(this.scopes[i], str);
|
||||
} catch (e) {
|
||||
if (/undefined variable/.test(e.message)) {
|
||||
continue;
|
||||
}
|
||||
if (/Cannot read property/.test(e.message)) {
|
||||
if (this.opts.strict_variables) {
|
||||
e.message += ': ' + str;
|
||||
throw e;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
e.message += ': ' + str;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.opts.strict_variables) {
|
||||
throw new TypeError('undefined variable: ' + str);
|
||||
}
|
||||
},
|
||||
set: function(k, v) {
|
||||
this.setPropertyByPath(this.scopes[this.scopes.length - 1], k, v);
|
||||
return this;
|
||||
},
|
||||
push: function(ctx) {
|
||||
assert(ctx, `trying to push ${ctx} into scopes`);
|
||||
return this.scopes.push(ctx);
|
||||
},
|
||||
pop: function() {
|
||||
return this.scopes.pop();
|
||||
},
|
||||
unshift: function(ctx) {
|
||||
assert(ctx, `trying to push ${ctx} into scopes`);
|
||||
return this.scopes.unshift(ctx);
|
||||
},
|
||||
shift: function() {
|
||||
return this.scopes.shift();
|
||||
},
|
||||
setPropertyByPath: function(obj, path, val) {
|
||||
if (_.isString(path)) {
|
||||
var paths = path.replace(/\[/g, '.').replace(/\]/g, '').split('.');
|
||||
for (var i = 0; i < paths.length; i++) {
|
||||
var key = paths[i];
|
||||
if (i === paths.length - 1) {
|
||||
return obj[key] = val;
|
||||
}
|
||||
if (undefined === obj[key]) obj[key] = {};
|
||||
// case for readonly objects
|
||||
obj = obj[key] || {};
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
getPropertyByPath: function(obj, path) {
|
||||
var paths = this.propertyAccessSeq(path + '');
|
||||
var varName = paths.shift();
|
||||
if (!obj.hasOwnProperty(varName)) {
|
||||
throw new TypeError('undefined variable');
|
||||
}
|
||||
var variable = obj[varName];
|
||||
paths.forEach(p => variable = variable[p]);
|
||||
return variable;
|
||||
},
|
||||
|
||||
/*
|
||||
* Parse property access sequence from access string
|
||||
* @example
|
||||
* accessSeq("foo.bar") // ['foo', 'bar']
|
||||
* accessSeq("foo['bar']") // ['foo', 'bar']
|
||||
* accessSeq("foo['b]r']") // ['foo', 'b]r']
|
||||
* accessSeq("foo[bar.coo]") // ['foo', 'bar'], for bar.coo == 'bar'
|
||||
*/
|
||||
propertyAccessSeq: function(str) {
|
||||
var seq = [],
|
||||
name = '';
|
||||
for (var i = 0; i < str.length; i++) {
|
||||
if (str[i] === '[') {
|
||||
seq.push(name);
|
||||
name = '';
|
||||
|
||||
var delemiter = str[i + 1];
|
||||
// foo[bar.coo]
|
||||
if (delemiter !== "'" && delemiter !== '"') {
|
||||
var j = matchRightBracket(str, i + 1);
|
||||
assert(j !== -1, `unbalanced []: ${str}`);
|
||||
name = str.slice(i + 1, j);
|
||||
// foo[1]
|
||||
if (lexical.isInteger(name)) {
|
||||
seq.push(name);
|
||||
}
|
||||
// foo["bar"]
|
||||
else {
|
||||
seq.push(this.get(name));
|
||||
}
|
||||
name = '';
|
||||
i = j;
|
||||
}
|
||||
// foo["bar"]
|
||||
else {
|
||||
j = str.indexOf(delemiter, i + 2);
|
||||
assert(j !== -1, `unbalanced ${delemiter}: ${str}`);
|
||||
name = str.slice(i + 2, j);
|
||||
seq.push(name);
|
||||
name = '';
|
||||
i = j + 1;
|
||||
}
|
||||
}
|
||||
// foo.bar
|
||||
else if (str[i] === ".") {
|
||||
seq.push(name);
|
||||
name = '';
|
||||
}
|
||||
//foo.bar
|
||||
else {
|
||||
name += str[i];
|
||||
}
|
||||
}
|
||||
if (name.length) seq.push(name);
|
||||
return seq;
|
||||
getAll: function () {
|
||||
var ctx = {}
|
||||
for (var i = this.scopes.length - 1; i >= 0; i--) {
|
||||
_.assign(ctx, this.scopes[i])
|
||||
}
|
||||
};
|
||||
|
||||
function matchRightBracket(str, begin) {
|
||||
var stack = 1; // count of '[' - count of ']'
|
||||
for (var i = begin; i < str.length; i++) {
|
||||
if (str[i] === '[') {
|
||||
stack++;
|
||||
}
|
||||
if (str[i] === ']') {
|
||||
stack--;
|
||||
if (stack === 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return ctx
|
||||
},
|
||||
get: function (str) {
|
||||
try {
|
||||
return this.getPropertyByPath(this.scopes, str)
|
||||
} catch (e) {
|
||||
if (!/undefined variable/.test(e.message) || this.opts.strict_variables) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
},
|
||||
set: function (k, v) {
|
||||
var scope = this.findScopeFor(k)
|
||||
setPropertyByPath(scope, k, v)
|
||||
return this
|
||||
},
|
||||
push: function (ctx) {
|
||||
assert(ctx, `trying to push ${ctx} into scopes`)
|
||||
return this.scopes.push(ctx)
|
||||
},
|
||||
pop: function () {
|
||||
return this.scopes.pop()
|
||||
},
|
||||
findScopeFor: function (key) {
|
||||
var i = this.scopes.length - 1
|
||||
while (i >= 0 && !(key in this.scopes[i])) {
|
||||
i--
|
||||
}
|
||||
if (i < 0) {
|
||||
i = this.scopes.length - 1
|
||||
}
|
||||
return this.scopes[i]
|
||||
},
|
||||
unshift: function (ctx) {
|
||||
assert(ctx, `trying to push ${ctx} into scopes`)
|
||||
return this.scopes.unshift(ctx)
|
||||
},
|
||||
shift: function () {
|
||||
return this.scopes.shift()
|
||||
},
|
||||
|
||||
getPropertyByPath: function (scopes, path) {
|
||||
var paths = this.propertyAccessSeq(path + '')
|
||||
if (!paths.length) {
|
||||
throw new TypeError('undefined variable: ' + path)
|
||||
}
|
||||
var key = paths.shift()
|
||||
var value = getValueFromScopes(key, scopes)
|
||||
if (_.isNil(value)) {
|
||||
throw new TypeError('undefined variable: ' + key)
|
||||
}
|
||||
while (paths.length) {
|
||||
key = paths.shift()
|
||||
value = getValueFromParent(key, value)
|
||||
if (_.isNil(value)) {
|
||||
throw new TypeError('undefined variable: ' + key)
|
||||
}
|
||||
}
|
||||
return value
|
||||
},
|
||||
|
||||
/*
|
||||
* Parse property access sequence from access string
|
||||
* @example
|
||||
* accessSeq("foo.bar") // ['foo', 'bar']
|
||||
* accessSeq("foo['bar']") // ['foo', 'bar']
|
||||
* accessSeq("foo['b]r']") // ['foo', 'b]r']
|
||||
* accessSeq("foo[bar.coo]") // ['foo', 'bar'], for bar.coo == 'bar'
|
||||
*/
|
||||
propertyAccessSeq: function (str) {
|
||||
var seq = []
|
||||
var name = ''
|
||||
var j
|
||||
var i = 0
|
||||
while (i < str.length) {
|
||||
switch (str[i]) {
|
||||
case '[':
|
||||
push()
|
||||
|
||||
var delemiter = str[i + 1]
|
||||
if (/['"]/.test(delemiter)) { // foo["bar"]
|
||||
j = str.indexOf(delemiter, i + 2)
|
||||
assert(j !== -1, `unbalanced ${delemiter}: ${str}`)
|
||||
name = str.slice(i + 2, j)
|
||||
push()
|
||||
i = j + 2
|
||||
} else { // foo[bar.coo]
|
||||
j = matchRightBracket(str, i + 1)
|
||||
assert(j !== -1, `unbalanced []: ${str}`)
|
||||
name = str.slice(i + 1, j)
|
||||
if (!lexical.isInteger(name)) { // foo[bar] vs. foo[1]
|
||||
name = this.get(name)
|
||||
}
|
||||
push()
|
||||
i = j + 1
|
||||
}
|
||||
break
|
||||
case '.':// foo.bar, foo[0].bar
|
||||
push()
|
||||
i++
|
||||
break
|
||||
default:// foo.bar
|
||||
name += str[i]
|
||||
i++
|
||||
}
|
||||
}
|
||||
push()
|
||||
return seq
|
||||
|
||||
function push () {
|
||||
if (name.length) seq.push(name)
|
||||
name = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
exports.factory = function(ctx, opts) {
|
||||
opts = _.assign({
|
||||
strict_variables: false,
|
||||
strict_filters: false,
|
||||
blocks: {},
|
||||
root: []
|
||||
}, opts);
|
||||
function setPropertyByPath (obj, path, val) {
|
||||
var paths = (path + '').replace(/\[/g, '.').replace(/\]/g, '').split('.')
|
||||
for (var i = 0; i < paths.length; i++) {
|
||||
var key = paths[i]
|
||||
if (!_.isObject(obj)) {
|
||||
// cannot set property of non-object
|
||||
return
|
||||
}
|
||||
// for end point
|
||||
if (i === paths.length - 1) {
|
||||
return (obj[key] = val)
|
||||
}
|
||||
// if path not exist
|
||||
if (undefined === obj[key]) {
|
||||
obj[key] = {}
|
||||
}
|
||||
obj = obj[key]
|
||||
}
|
||||
}
|
||||
|
||||
ctx = _.assign(ctx, {
|
||||
liquid: opts
|
||||
});
|
||||
function getValueFromParent (key, value) {
|
||||
return (key === 'size' && (_.isArray(value) || _.isString(value)))
|
||||
? value.length
|
||||
: value[key]
|
||||
}
|
||||
|
||||
var scope = Object.create(Scope);
|
||||
scope.opts = opts;
|
||||
scope.scopes = [ctx];
|
||||
return scope;
|
||||
};
|
||||
function getValueFromScopes (key, scopes) {
|
||||
for (var i = scopes.length - 1; i > -1; i--) {
|
||||
var scope = scopes[i]
|
||||
if (scope.hasOwnProperty(key)) {
|
||||
return scope[key]
|
||||
}
|
||||
}
|
||||
throw new TypeError('undefined variable: ' + key)
|
||||
}
|
||||
|
||||
function matchRightBracket (str, begin) {
|
||||
var stack = 1 // count of '[' - count of ']'
|
||||
for (var i = begin; i < str.length; i++) {
|
||||
if (str[i] === '[') {
|
||||
stack++
|
||||
}
|
||||
if (str[i] === ']') {
|
||||
stack--
|
||||
if (stack === 0) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
exports.factory = function (ctx, opts) {
|
||||
var defaultOptions = {
|
||||
dynamicPartials: true,
|
||||
strict_variables: false,
|
||||
strict_filters: false,
|
||||
blocks: {},
|
||||
root: []
|
||||
}
|
||||
var scope = Object.create(Scope)
|
||||
scope.opts = _.assign(defaultOptions, opts)
|
||||
scope.scopes = [ctx || {}]
|
||||
return scope
|
||||
}
|
||||
|
||||
+41
-41
@@ -1,56 +1,56 @@
|
||||
const operators = require('./operators.js');
|
||||
const lexical = require('./lexical.js');
|
||||
const assert = require('../src/util/assert.js');
|
||||
const operators = require('./operators.js')(isTruthy)
|
||||
const lexical = require('./lexical.js')
|
||||
const assert = require('../src/util/assert.js')
|
||||
|
||||
function evalExp(exp, scope) {
|
||||
assert(scope, 'unable to evalExp: scope undefined');
|
||||
var operatorREs = lexical.operators,
|
||||
match;
|
||||
for (var i = 0; i < operatorREs.length; i++) {
|
||||
var operatorRE = operatorREs[i];
|
||||
var expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`);
|
||||
if (match = exp.match(expRE)) {
|
||||
var l = evalExp(match[1], scope);
|
||||
var op = operators[match[2].trim()];
|
||||
var r = evalExp(match[3], scope);
|
||||
return op(l, r);
|
||||
}
|
||||
function evalExp (exp, scope) {
|
||||
assert(scope, 'unable to evalExp: scope undefined')
|
||||
var operatorREs = lexical.operators
|
||||
var match
|
||||
for (var i = 0; i < operatorREs.length; i++) {
|
||||
var operatorRE = operatorREs[i]
|
||||
var expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`)
|
||||
if ((match = exp.match(expRE))) {
|
||||
var l = evalExp(match[1], scope)
|
||||
var op = operators[match[2].trim()]
|
||||
var r = evalExp(match[3], scope)
|
||||
return op(l, r)
|
||||
}
|
||||
}
|
||||
|
||||
if (match = exp.match(lexical.rangeLine)) {
|
||||
var low = evalValue(match[1], scope),
|
||||
high = evalValue(match[2], scope);
|
||||
var range = [];
|
||||
for (var j = low; j <= high; j++) {
|
||||
range.push(j);
|
||||
}
|
||||
return range;
|
||||
if ((match = exp.match(lexical.rangeLine))) {
|
||||
var low = evalValue(match[1], scope)
|
||||
var high = evalValue(match[2], scope)
|
||||
var range = []
|
||||
for (var j = low; j <= high; j++) {
|
||||
range.push(j)
|
||||
}
|
||||
return range
|
||||
}
|
||||
|
||||
return evalValue(exp, scope);
|
||||
return evalValue(exp, scope)
|
||||
}
|
||||
|
||||
function evalValue(str, scope) {
|
||||
str = str && str.trim();
|
||||
if (!str) return undefined;
|
||||
function evalValue (str, scope) {
|
||||
str = str && str.trim()
|
||||
if (!str) return undefined
|
||||
|
||||
if (lexical.isLiteral(str)) {
|
||||
return lexical.parseLiteral(str);
|
||||
}
|
||||
if (lexical.isVariable(str)) {
|
||||
return scope.get(str);
|
||||
}
|
||||
if (lexical.isLiteral(str)) {
|
||||
return lexical.parseLiteral(str)
|
||||
}
|
||||
if (lexical.isVariable(str)) {
|
||||
return scope.get(str)
|
||||
}
|
||||
throw new TypeError(`cannot eval '${str}' as value`)
|
||||
}
|
||||
|
||||
function isTruthy(val) {
|
||||
if (val instanceof Array) return !!val.length;
|
||||
return !!val;
|
||||
function isTruthy (val) {
|
||||
return !isFalsy(val)
|
||||
}
|
||||
|
||||
function isFalsy(val) {
|
||||
return !isTruthy(val);
|
||||
function isFalsy (val) {
|
||||
return val === false || undefined === val || val === null
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
evalExp, evalValue, isTruthy, isFalsy
|
||||
};
|
||||
evalExp, evalValue, isTruthy, isFalsy
|
||||
}
|
||||
|
||||
+53
-64
@@ -1,73 +1,62 @@
|
||||
const lexical = require('./lexical.js');
|
||||
const _ = require('./util/underscore.js');
|
||||
const Promise = require('any-promise');
|
||||
const Syntax = require('./syntax.js');
|
||||
const assert = require('./util/assert.js');
|
||||
const lexical = require('./lexical.js')
|
||||
const Syntax = require('./syntax.js')
|
||||
const assert = require('./util/assert.js')
|
||||
|
||||
function hash(markup, scope) {
|
||||
var obj = {},
|
||||
match;
|
||||
lexical.hashCapture.lastIndex = 0;
|
||||
while (match = lexical.hashCapture.exec(markup)) {
|
||||
var k = match[1],
|
||||
v = match[2];
|
||||
obj[k] = Syntax.evalValue(v, scope);
|
||||
}
|
||||
return obj;
|
||||
function hash (markup, scope) {
|
||||
var obj = {}
|
||||
var match
|
||||
lexical.hashCapture.lastIndex = 0
|
||||
while ((match = lexical.hashCapture.exec(markup))) {
|
||||
var k = match[1]
|
||||
var v = match[2]
|
||||
obj[k] = Syntax.evalValue(v, scope)
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
module.exports = function() {
|
||||
var tagImpls = {};
|
||||
module.exports = function () {
|
||||
var tagImpls = {}
|
||||
|
||||
var _tagInstance = {
|
||||
render: function(scope) {
|
||||
var obj = hash(this.token.args, scope);
|
||||
var impl = this.tagImpl;
|
||||
if (typeof impl.render !== 'function') {
|
||||
return Promise.resolve('');
|
||||
}
|
||||
return Promise.resolve()
|
||||
.then(() => typeof impl.render === 'function' ?
|
||||
impl.render(scope, obj) : '')
|
||||
.catch(function(e) {
|
||||
if (_.isError(e)) {
|
||||
throw e;
|
||||
}
|
||||
var msg = `Please reject with an Error in ${impl.render}, got ${e}`;
|
||||
throw new Error(msg);
|
||||
});
|
||||
},
|
||||
parse: function(token, tokens) {
|
||||
this.type = 'tag';
|
||||
this.token = token;
|
||||
this.name = token.name;
|
||||
var _tagInstance = {
|
||||
render: function (scope) {
|
||||
var obj = hash(this.token.args, scope)
|
||||
var impl = this.tagImpl
|
||||
if (typeof impl.render !== 'function') {
|
||||
return Promise.resolve('')
|
||||
}
|
||||
return Promise.resolve().then(() => impl.render(scope, obj))
|
||||
},
|
||||
parse: function (token, tokens) {
|
||||
this.type = 'tag'
|
||||
this.token = token
|
||||
this.name = token.name
|
||||
|
||||
var tagImpl = tagImpls[this.name];
|
||||
assert(tagImpl, `tag ${this.name} not found`);
|
||||
this.tagImpl = Object.create(tagImpl);
|
||||
if (this.tagImpl.parse) {
|
||||
this.tagImpl.parse(token, tokens);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function register(name, tag) {
|
||||
tagImpls[name] = tag;
|
||||
var tagImpl = tagImpls[this.name]
|
||||
assert(tagImpl, `tag ${this.name} not found`)
|
||||
this.tagImpl = Object.create(tagImpl)
|
||||
if (this.tagImpl.parse) {
|
||||
this.tagImpl.parse(token, tokens)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function construct(token, tokens) {
|
||||
var instance = Object.create(_tagInstance);
|
||||
instance.parse(token, tokens);
|
||||
return instance;
|
||||
}
|
||||
function register (name, tag) {
|
||||
tagImpls[name] = tag
|
||||
}
|
||||
|
||||
function clear() {
|
||||
tagImpls = {};
|
||||
}
|
||||
function construct (token, tokens) {
|
||||
var instance = Object.create(_tagInstance)
|
||||
instance.parse(token, tokens)
|
||||
return instance
|
||||
}
|
||||
|
||||
return {
|
||||
construct,
|
||||
register,
|
||||
clear
|
||||
};
|
||||
};
|
||||
function clear () {
|
||||
tagImpls = {}
|
||||
}
|
||||
|
||||
return {
|
||||
construct,
|
||||
register,
|
||||
clear
|
||||
}
|
||||
}
|
||||
|
||||
+79
-61
@@ -1,73 +1,91 @@
|
||||
const lexical = require('./lexical.js');
|
||||
const TokenizationError = require('./util/error.js').TokenizationError;
|
||||
const _ = require('./util/underscore.js');
|
||||
const assert = require('../src/util/assert.js');
|
||||
const lexical = require('./lexical.js')
|
||||
const TokenizationError = require('./util/error.js').TokenizationError
|
||||
const _ = require('./util/underscore.js')
|
||||
const whiteSpaceCtrl = require('./whitespace-ctrl.js')
|
||||
const assert = require('./util/assert.js')
|
||||
|
||||
function parse(html) {
|
||||
assert(_.isString(html), 'illegal input type');
|
||||
function parse (input, file, options) {
|
||||
assert(_.isString(input), 'illegal input')
|
||||
|
||||
var tokens = [];
|
||||
var syntax = /({%(.*?)%})|({{(.*?)}})/g;
|
||||
var result, htmlFragment, token;
|
||||
var lastMatchEnd = 0, lastMatchBegin = -1, parsedLinesCount = 0;
|
||||
var rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
|
||||
var currIndent = 0
|
||||
var lineNumber = LineNumber(input)
|
||||
var lastMatchEnd = 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
|
||||
});
|
||||
}
|
||||
// tag appeared
|
||||
if (result[1]) {
|
||||
token = factory('tag', 1, result);
|
||||
|
||||
var match = token.value.match(lexical.tagLine);
|
||||
if (!match) {
|
||||
throw new TokenizationError(`illegal tag syntax`, token);
|
||||
}
|
||||
token.name = match[1];
|
||||
token.args = match[2];
|
||||
|
||||
tokens.push(token);
|
||||
}
|
||||
// output
|
||||
else { token = factory('output', 3, result);
|
||||
tokens.push(token);
|
||||
}
|
||||
lastMatchEnd = syntax.lastIndex;
|
||||
for (var match; (match = rLiquid.exec(input)); lastMatchEnd = rLiquid.lastIndex) {
|
||||
if (match.index > lastMatchEnd) {
|
||||
tokens.push(parseHTMLToken(lastMatchEnd, match.index))
|
||||
}
|
||||
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
|
||||
|
||||
// remaining html
|
||||
if (html.length > lastMatchEnd) {
|
||||
htmlFragment = html.slice(lastMatchEnd, html.length);
|
||||
tokens.push({
|
||||
type: 'html',
|
||||
raw: htmlFragment,
|
||||
value: htmlFragment
|
||||
});
|
||||
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
|
||||
}
|
||||
return tokens;
|
||||
if (!match) {
|
||||
throw new TokenizationError(`illegal tag syntax`, token)
|
||||
}
|
||||
token.name = match[1]
|
||||
token.args = match[2]
|
||||
return token
|
||||
}
|
||||
|
||||
function factory(type, offset, match) {
|
||||
return {
|
||||
type: type,
|
||||
raw: match[offset],
|
||||
value: match[offset + 1].trim(),
|
||||
line: getLineNum(match),
|
||||
input: html
|
||||
};
|
||||
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 getLineNum(match) {
|
||||
var lines = match.input.slice(lastMatchBegin + 1, match.index).split('\n');
|
||||
parsedLinesCount += lines.length - 1;
|
||||
lastMatchBegin = match.index;
|
||||
return parsedLinesCount + 1;
|
||||
function parseHTMLToken (begin, end) {
|
||||
var htmlFragment = input.slice(begin, end)
|
||||
currIndent = _.last((htmlFragment).split('\n')).length
|
||||
|
||||
return {
|
||||
type: 'html',
|
||||
raw: htmlFragment,
|
||||
value: htmlFragment
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
exports.parse = parse;
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
exports.parse = parse
|
||||
exports.whiteSpaceCtrl = whiteSpaceCtrl
|
||||
|
||||
+7
-10
@@ -1,13 +1,10 @@
|
||||
const AssertionError = require('./error.js').AssertionError;
|
||||
const AssertionError = require('./error.js').AssertionError
|
||||
|
||||
function assert(predicate, message) {
|
||||
if (!predicate) {
|
||||
if (message instanceof Error) {
|
||||
throw message;
|
||||
}
|
||||
var message = message || `expect ${predicate} to be true`;
|
||||
throw new AssertionError(message);
|
||||
}
|
||||
function assert (predicate, message) {
|
||||
if (!predicate) {
|
||||
message = message || `expect ${predicate} to be true`
|
||||
throw new AssertionError(message)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = assert;
|
||||
module.exports = assert
|
||||
|
||||
+102
-89
@@ -1,95 +1,108 @@
|
||||
const _ = require('./underscore.js');
|
||||
const _ = require('./underscore.js')
|
||||
|
||||
function TokenizationError(message, token) {
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
}
|
||||
this.name = this.constructor.name;
|
||||
|
||||
this.input = token.input;
|
||||
this.line = token.line;
|
||||
|
||||
var context = mkContext(token.input, token.line);
|
||||
this.message = message + '\n' + context;
|
||||
}
|
||||
TokenizationError.prototype = Object.create(Error.prototype);
|
||||
TokenizationError.prototype.constructor = TokenizationError;
|
||||
|
||||
function ParseError(e, token) {
|
||||
this.name = this.constructor.name;
|
||||
this.stack = e.stack;
|
||||
|
||||
this.input = token.input;
|
||||
this.line = token.line;
|
||||
|
||||
var context = mkContext(token.input, token.line);
|
||||
this.message = e.message + '\n' + context;
|
||||
}
|
||||
ParseError.prototype = Object.create(Error.prototype);
|
||||
ParseError.prototype.constructor = ParseError;
|
||||
|
||||
function RenderError(e, tpl) {
|
||||
this.name = this.constructor.name;
|
||||
this.stack = e.stack;
|
||||
|
||||
this.input = tpl.token.input;
|
||||
this.line = tpl.token.line;
|
||||
|
||||
var context = mkContext(tpl.token.input, tpl.token.line);
|
||||
this.message = e.message + '\n' + context;
|
||||
}
|
||||
RenderError.prototype = Object.create(Error.prototype);
|
||||
RenderError.prototype.constructor = RenderError;
|
||||
|
||||
function RenderBreakError(message) {
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
}
|
||||
this.name = this.constructor.name;
|
||||
this.message = message || '';
|
||||
}
|
||||
RenderBreakError.prototype = Object.create(Error.prototype);
|
||||
RenderBreakError.prototype.constructor = RenderBreakError;
|
||||
|
||||
function AssertionError(message) {
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
}
|
||||
this.name = this.constructor.name;
|
||||
this.message = message;
|
||||
}
|
||||
AssertionError.prototype = Object.create(Error.prototype);
|
||||
AssertionError.prototype.constructor = AssertionError;
|
||||
|
||||
function mkContext(input, line) {
|
||||
var lines = input.split('\n');
|
||||
var begin = Math.max(line - 2, 1);
|
||||
var end = Math.min(line + 3, lines.length);
|
||||
|
||||
var context = _
|
||||
.range(begin, end + 1)
|
||||
.map(l => [
|
||||
(l === line) ? '>> ' : ' ',
|
||||
align(l, end),
|
||||
'| ',
|
||||
lines[l - 1]
|
||||
].join(''))
|
||||
.join('\n');
|
||||
|
||||
return context;
|
||||
function initError () {
|
||||
this.name = this.constructor.name
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, this.constructor)
|
||||
}
|
||||
}
|
||||
|
||||
function align(n, max) {
|
||||
var length = (max + '').length;
|
||||
var str = n + '';
|
||||
var blank = Array(length - str.length).join(' ');
|
||||
return blank + str;
|
||||
function initLiquidError (err, token) {
|
||||
initError.call(this)
|
||||
|
||||
this.input = token.input
|
||||
this.line = token.line
|
||||
this.file = token.file
|
||||
|
||||
var context = mkContext(token.input, token.line)
|
||||
this.message = mkMessage(err.message, token)
|
||||
this.stack = context +
|
||||
'\n' + (this.stack || this.message) +
|
||||
(err.stack ? '\nFrom ' + err.stack : '')
|
||||
}
|
||||
|
||||
function TokenizationError (message, token) {
|
||||
initLiquidError.call(this, {message: message}, token)
|
||||
}
|
||||
TokenizationError.prototype = Object.create(Error.prototype)
|
||||
TokenizationError.prototype.constructor = TokenizationError
|
||||
|
||||
function ParseError (e, token) {
|
||||
_.assign(this, e)
|
||||
this.originalError = e
|
||||
|
||||
initLiquidError.call(this, e, token)
|
||||
}
|
||||
ParseError.prototype = Object.create(Error.prototype)
|
||||
ParseError.prototype.constructor = ParseError
|
||||
|
||||
function RenderError (e, tpl) {
|
||||
// return the original render error
|
||||
if (e instanceof RenderError) {
|
||||
return e
|
||||
}
|
||||
_.assign(this, e)
|
||||
this.originalError = e
|
||||
|
||||
initLiquidError.call(this, e, tpl.token)
|
||||
}
|
||||
RenderError.prototype = Object.create(Error.prototype)
|
||||
RenderError.prototype.constructor = RenderError
|
||||
|
||||
function RenderBreakError (message) {
|
||||
initError.call(this)
|
||||
this.message = message + ''
|
||||
}
|
||||
RenderBreakError.prototype = Object.create(Error.prototype)
|
||||
RenderBreakError.prototype.constructor = RenderBreakError
|
||||
|
||||
function AssertionError (message) {
|
||||
initError.call(this)
|
||||
this.message = message + ''
|
||||
}
|
||||
AssertionError.prototype = Object.create(Error.prototype)
|
||||
AssertionError.prototype.constructor = AssertionError
|
||||
|
||||
function mkContext (input, line) {
|
||||
var lines = input.split('\n')
|
||||
var begin = Math.max(line - 2, 1)
|
||||
var end = Math.min(line + 3, lines.length)
|
||||
|
||||
var context = _
|
||||
.range(begin, end + 1)
|
||||
.map(l => [
|
||||
(l === line) ? '>> ' : ' ',
|
||||
align(l, end),
|
||||
'| ',
|
||||
lines[l - 1]
|
||||
].join(''))
|
||||
.join('\n')
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function align (n, max) {
|
||||
var length = (max + '').length
|
||||
var str = n + ''
|
||||
var blank = Array(length - str.length).join(' ')
|
||||
return blank + str
|
||||
}
|
||||
|
||||
function mkMessage (msg, token) {
|
||||
msg = msg || ''
|
||||
if (token.file) {
|
||||
msg += ', file:' + token.file
|
||||
}
|
||||
if (token.line) {
|
||||
msg += ', line:' + token.line
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TokenizationError,
|
||||
ParseError,
|
||||
RenderBreakError,
|
||||
AssertionError,
|
||||
RenderError
|
||||
};
|
||||
TokenizationError,
|
||||
ParseError,
|
||||
RenderBreakError,
|
||||
AssertionError,
|
||||
RenderError
|
||||
}
|
||||
|
||||
+14
-14
@@ -1,20 +1,20 @@
|
||||
const fs = require('fs');
|
||||
const fs = require('fs')
|
||||
|
||||
function readFileAsync(filepath) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
fs.readFile(filepath, 'utf8', function(err, content) {
|
||||
err ? reject(err) : resolve(content);
|
||||
});
|
||||
});
|
||||
function readFileAsync (filepath) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
fs.readFile(filepath, 'utf8', function (err, content) {
|
||||
err ? reject(err) : resolve(content)
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
function statFileAsync(path) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
fs.stat(path, (err, stat) => err ? reject(err) : resolve(stat))
|
||||
});
|
||||
function statFileAsync (path) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
fs.stat(path, (err, stat) => err ? reject(err) : resolve(stat))
|
||||
})
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
readFileAsync,
|
||||
statFileAsync
|
||||
};
|
||||
readFileAsync,
|
||||
statFileAsync
|
||||
}
|
||||
|
||||
+19
-21
@@ -1,35 +1,33 @@
|
||||
const Promise = require('any-promise');
|
||||
|
||||
/*
|
||||
* Call functions in serial until someone resolved.
|
||||
* @param {Array} iterable the array to iterate with.
|
||||
* @param {Array} iteratee returns a new promise.
|
||||
* The iteratee is invoked with three arguments: (value, index, iterable).
|
||||
* The iteratee is invoked with three arguments: (value, index, iterable).
|
||||
*/
|
||||
function anySeries(iterable, iteratee) {
|
||||
var ret = Promise.reject(new Error('init'));
|
||||
iterable.forEach(function(item, idx) {
|
||||
ret = ret.catch(e => iteratee(item, idx, iterable));
|
||||
});
|
||||
return ret;
|
||||
function anySeries (iterable, iteratee) {
|
||||
var ret = Promise.reject(new Error('init'))
|
||||
iterable.forEach(function (item, idx) {
|
||||
ret = ret.catch(e => iteratee(item, idx, iterable))
|
||||
})
|
||||
return ret
|
||||
}
|
||||
|
||||
/*
|
||||
* Call functions in serial until someone rejected.
|
||||
* @param {Array} iterable the array to iterate with.
|
||||
* @param {Array} iteratee returns a new promise.
|
||||
* The iteratee is invoked with three arguments: (value, index, iterable).
|
||||
* The iteratee is invoked with three arguments: (value, index, iterable).
|
||||
*/
|
||||
function mapSeries(iterable, iteratee) {
|
||||
var ret = Promise.resolve('init');
|
||||
var result = [];
|
||||
iterable.forEach(function(item, idx) {
|
||||
ret = ret
|
||||
.then(() => iteratee(item, idx, iterable))
|
||||
.then(x => result.push(x));
|
||||
});
|
||||
return ret.then(() => result);
|
||||
function mapSeries (iterable, iteratee) {
|
||||
var ret = Promise.resolve('init')
|
||||
var result = []
|
||||
iterable.forEach(function (item, idx) {
|
||||
ret = ret
|
||||
.then(() => iteratee(item, idx, iterable))
|
||||
.then(x => result.push(x))
|
||||
})
|
||||
return ret.then(() => result)
|
||||
}
|
||||
|
||||
exports.anySeries = anySeries;
|
||||
exports.mapSeries = mapSeries;
|
||||
exports.anySeries = anySeries
|
||||
exports.mapSeries = mapSeries
|
||||
|
||||
+180
-181
@@ -1,200 +1,199 @@
|
||||
var monthNames = [
|
||||
"January", "February", "March", "April", "May", "June", "July", "August",
|
||||
"September", "October", "November", "December"
|
||||
];
|
||||
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
|
||||
'September', 'October', 'November', 'December'
|
||||
]
|
||||
var monthNamesShort = [
|
||||
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
|
||||
"Nov", "Dec"
|
||||
];
|
||||
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
|
||||
'Nov', 'Dec'
|
||||
]
|
||||
var dayNames = [
|
||||
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
|
||||
];
|
||||
var dayNamesShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
||||
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
|
||||
]
|
||||
var dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
||||
var suffixes = {
|
||||
1: 'st',
|
||||
2: 'nd',
|
||||
3: 'rd',
|
||||
'default': 'th'
|
||||
};
|
||||
1: 'st',
|
||||
2: 'nd',
|
||||
3: 'rd',
|
||||
'default': 'th'
|
||||
}
|
||||
|
||||
// prototype extensions
|
||||
var _date = {
|
||||
daysInMonth: function(d) {
|
||||
var feb = _date.isLeapYear(d) ? 29 : 28;
|
||||
return [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
},
|
||||
daysInMonth: function (d) {
|
||||
var feb = _date.isLeapYear(d) ? 29 : 28
|
||||
return [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
|
||||
},
|
||||
|
||||
getDayOfYear: function(d) {
|
||||
var num = 0;
|
||||
for (var i = 0; i < d.getMonth(); ++i) {
|
||||
num += _date.daysInMonth(d)[i];
|
||||
}
|
||||
return num + d.getDate();
|
||||
},
|
||||
|
||||
// Startday is an integer of which day to start the week measuring from
|
||||
// TODO: that comment was retarted. fix it.
|
||||
getWeekOfYear: function(d, startDay) {
|
||||
// Skip to startDay of this week
|
||||
var now = this.getDayOfYear(d) + (startDay - d.getDay());
|
||||
// Find the first startDay of the year
|
||||
var jan1 = new Date(d.getFullYear(), 0, 1);
|
||||
var then = (7 - jan1.getDay() + startDay);
|
||||
return _number.pad(Math.floor((now - then) / 7) + 1, 2);
|
||||
},
|
||||
|
||||
isLeapYear: function(d) {
|
||||
var year = d.getFullYear();
|
||||
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)));
|
||||
},
|
||||
|
||||
getSuffix: function(d) {
|
||||
var str = d.getDate().toString();
|
||||
var index = parseInt(str.slice(-1));
|
||||
return suffixes[index] || suffixes['default'];
|
||||
},
|
||||
|
||||
century: function(d) {
|
||||
return parseInt(d.getFullYear().toString().substring(0, 2), 10);
|
||||
getDayOfYear: function (d) {
|
||||
var num = 0
|
||||
for (var i = 0; i < d.getMonth(); ++i) {
|
||||
num += _date.daysInMonth(d)[i]
|
||||
}
|
||||
};
|
||||
return num + d.getDate()
|
||||
},
|
||||
|
||||
// Startday is an integer of which day to start the week measuring from
|
||||
// TODO: that comment was retarted. fix it.
|
||||
getWeekOfYear: function (d, startDay) {
|
||||
// Skip to startDay of this week
|
||||
var now = this.getDayOfYear(d) + (startDay - d.getDay())
|
||||
// Find the first startDay of the year
|
||||
var jan1 = new Date(d.getFullYear(), 0, 1)
|
||||
var then = (7 - jan1.getDay() + startDay)
|
||||
return _number.pad(Math.floor((now - then) / 7) + 1, 2)
|
||||
},
|
||||
|
||||
isLeapYear: function (d) {
|
||||
var year = d.getFullYear()
|
||||
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)))
|
||||
},
|
||||
|
||||
getSuffix: function (d) {
|
||||
var str = d.getDate().toString()
|
||||
var index = parseInt(str.slice(-1))
|
||||
return suffixes[index] || suffixes['default']
|
||||
},
|
||||
|
||||
century: function (d) {
|
||||
return parseInt(d.getFullYear().toString().substring(0, 2), 10)
|
||||
}
|
||||
}
|
||||
|
||||
var _number = {
|
||||
pad: function(value, size, ch) {
|
||||
if (!ch) ch = '0';
|
||||
var result = value.toString();
|
||||
var pad = size - result.length;
|
||||
pad: function (value, size, ch) {
|
||||
if (!ch) ch = '0'
|
||||
var result = value.toString()
|
||||
var pad = size - result.length
|
||||
|
||||
while (pad-- > 0) {
|
||||
result = ch + result;
|
||||
}
|
||||
|
||||
return result;
|
||||
while (pad-- > 0) {
|
||||
result = ch + result
|
||||
}
|
||||
};
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
var format_codes = {
|
||||
a: function(d) {
|
||||
return dayNamesShort[d.getDay()];
|
||||
},
|
||||
A: function(d) {
|
||||
return dayNames[d.getDay()];
|
||||
},
|
||||
b: function(d) {
|
||||
return monthNamesShort[d.getMonth()];
|
||||
},
|
||||
B: function(d) {
|
||||
return monthNames[d.getMonth()];
|
||||
},
|
||||
c: function(d) {
|
||||
return d.toLocaleString();
|
||||
},
|
||||
C: function(d) {
|
||||
return _date.century(d);
|
||||
},
|
||||
d: function(d) {
|
||||
return _number.pad(d.getDate(), 2);
|
||||
},
|
||||
e: function(d) {
|
||||
return _number.pad(d.getDate(), 2, ' ');
|
||||
},
|
||||
H: function(d) {
|
||||
return _number.pad(d.getHours(), 2);
|
||||
},
|
||||
I: function(d) {
|
||||
return _number.pad(d.getHours() % 12 || 12, 2);
|
||||
},
|
||||
j: function(d) {
|
||||
return _number.pad(_date.getDayOfYear(d), 3);
|
||||
},
|
||||
k: function(d) {
|
||||
return _number.pad(d.getHours(), 2, ' ');
|
||||
},
|
||||
l: function(d) {
|
||||
return _number.pad(d.getHours() % 12 || 12, 2, ' ');
|
||||
},
|
||||
L: function(d) {
|
||||
return _number.pad(d.getMilliseconds(), 3);
|
||||
},
|
||||
m: function(d) {
|
||||
return _number.pad(d.getMonth() + 1, 2);
|
||||
},
|
||||
M: function(d) {
|
||||
return _number.pad(d.getMinutes(), 2);
|
||||
},
|
||||
p: function(d) {
|
||||
return (d.getHours() < 12 ? 'AM' : 'PM');
|
||||
},
|
||||
P: function(d) {
|
||||
return (d.getHours() < 12 ? 'am' : 'pm');
|
||||
},
|
||||
q: function(d) {
|
||||
return _date.getSuffix(d);
|
||||
},
|
||||
s: function(d) {
|
||||
return Math.round(d.valueOf() / 1000);
|
||||
},
|
||||
S: function(d) {
|
||||
return _number.pad(d.getSeconds(), 2);
|
||||
},
|
||||
u: function(d) {
|
||||
return d.getDay() || 7;
|
||||
},
|
||||
U: function(d) {
|
||||
return _date.getWeekOfYear(d, 0);
|
||||
},
|
||||
w: function(d) {
|
||||
return d.getDay();
|
||||
},
|
||||
W: function(d) {
|
||||
return _date.getWeekOfYear(d, 1);
|
||||
},
|
||||
x: function(d) {
|
||||
return d.toLocaleDateString();
|
||||
},
|
||||
X: function(d) {
|
||||
return d.toLocaleTimeString();
|
||||
},
|
||||
y: function(d) {
|
||||
return d.getFullYear().toString().substring(2, 4);
|
||||
},
|
||||
Y: function(d) {
|
||||
return d.getFullYear();
|
||||
},
|
||||
z: function(d) {
|
||||
var tz = d.getTimezoneOffset() / 60 * 100;
|
||||
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4);
|
||||
},
|
||||
"%": function() {
|
||||
return '%';
|
||||
var formatCodes = {
|
||||
a: function (d) {
|
||||
return dayNamesShort[d.getDay()]
|
||||
},
|
||||
A: function (d) {
|
||||
return dayNames[d.getDay()]
|
||||
},
|
||||
b: function (d) {
|
||||
return monthNamesShort[d.getMonth()]
|
||||
},
|
||||
B: function (d) {
|
||||
return monthNames[d.getMonth()]
|
||||
},
|
||||
c: function (d) {
|
||||
return d.toLocaleString()
|
||||
},
|
||||
C: function (d) {
|
||||
return _date.century(d)
|
||||
},
|
||||
d: function (d) {
|
||||
return _number.pad(d.getDate(), 2)
|
||||
},
|
||||
e: function (d) {
|
||||
return _number.pad(d.getDate(), 2, ' ')
|
||||
},
|
||||
H: function (d) {
|
||||
return _number.pad(d.getHours(), 2)
|
||||
},
|
||||
I: function (d) {
|
||||
return _number.pad(d.getHours() % 12 || 12, 2)
|
||||
},
|
||||
j: function (d) {
|
||||
return _number.pad(_date.getDayOfYear(d), 3)
|
||||
},
|
||||
k: function (d) {
|
||||
return _number.pad(d.getHours(), 2, ' ')
|
||||
},
|
||||
l: function (d) {
|
||||
return _number.pad(d.getHours() % 12 || 12, 2, ' ')
|
||||
},
|
||||
L: function (d) {
|
||||
return _number.pad(d.getMilliseconds(), 3)
|
||||
},
|
||||
m: function (d) {
|
||||
return _number.pad(d.getMonth() + 1, 2)
|
||||
},
|
||||
M: function (d) {
|
||||
return _number.pad(d.getMinutes(), 2)
|
||||
},
|
||||
p: function (d) {
|
||||
return (d.getHours() < 12 ? 'AM' : 'PM')
|
||||
},
|
||||
P: function (d) {
|
||||
return (d.getHours() < 12 ? 'am' : 'pm')
|
||||
},
|
||||
q: function (d) {
|
||||
return _date.getSuffix(d)
|
||||
},
|
||||
s: function (d) {
|
||||
return Math.round(d.valueOf() / 1000)
|
||||
},
|
||||
S: function (d) {
|
||||
return _number.pad(d.getSeconds(), 2)
|
||||
},
|
||||
u: function (d) {
|
||||
return d.getDay() || 7
|
||||
},
|
||||
U: function (d) {
|
||||
return _date.getWeekOfYear(d, 0)
|
||||
},
|
||||
w: function (d) {
|
||||
return d.getDay()
|
||||
},
|
||||
W: function (d) {
|
||||
return _date.getWeekOfYear(d, 1)
|
||||
},
|
||||
x: function (d) {
|
||||
return d.toLocaleDateString()
|
||||
},
|
||||
X: function (d) {
|
||||
return d.toLocaleTimeString()
|
||||
},
|
||||
y: function (d) {
|
||||
return d.getFullYear().toString().substring(2, 4)
|
||||
},
|
||||
Y: function (d) {
|
||||
return d.getFullYear()
|
||||
},
|
||||
z: function (d) {
|
||||
var tz = d.getTimezoneOffset() / 60 * 100
|
||||
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4)
|
||||
},
|
||||
'%': function () {
|
||||
return '%'
|
||||
}
|
||||
}
|
||||
formatCodes.h = formatCodes.b
|
||||
formatCodes.N = formatCodes.L
|
||||
|
||||
var strftime = function (d, format) {
|
||||
var output = ''
|
||||
var remaining = format
|
||||
|
||||
while (true) {
|
||||
var r = /%./g
|
||||
var results = r.exec(remaining)
|
||||
|
||||
// No more format codes. Add the remaining text and return
|
||||
if (!results) {
|
||||
return output + remaining
|
||||
}
|
||||
};
|
||||
format_codes.h = format_codes.b;
|
||||
format_codes.N = format_codes.L;
|
||||
|
||||
var strftime = function(d, format) {
|
||||
var output = '';
|
||||
var remaining = format;
|
||||
// Add the preceding text
|
||||
output += remaining.slice(0, r.lastIndex - 2)
|
||||
remaining = remaining.slice(r.lastIndex)
|
||||
|
||||
while (true) {
|
||||
var r = /%./g;
|
||||
var results = r.exec(remaining);
|
||||
// Add the format code
|
||||
var ch = results[0].charAt(1)
|
||||
var func = formatCodes[ch]
|
||||
output += func ? func.call(this, d) : '%' + ch
|
||||
}
|
||||
}
|
||||
|
||||
// No more format codes. Add the remaining text and return
|
||||
if (!results) {
|
||||
return output + remaining;
|
||||
}
|
||||
|
||||
// Add the preceding text
|
||||
output += remaining.slice(0, r.lastIndex - 2);
|
||||
remaining = remaining.slice(r.lastIndex);
|
||||
|
||||
// Add the format code
|
||||
var ch = results[0].charAt(1);
|
||||
var func = format_codes[ch];
|
||||
output += func ? func.call(this, d) : '%' + ch;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = strftime;
|
||||
module.exports = strftime
|
||||
|
||||
+87
-81
@@ -1,41 +1,52 @@
|
||||
const toStr = Object.prototype.toString
|
||||
|
||||
/*
|
||||
* Checks if value is classified as a String primitive or object.
|
||||
* @param {any} value The value to check.
|
||||
* @return {Boolean} Returns true if value is a string, else false.
|
||||
*/
|
||||
function isString(value) {
|
||||
return value instanceof String || typeof value === 'string';
|
||||
function isString (value) {
|
||||
return value instanceof String || typeof value === 'string'
|
||||
}
|
||||
|
||||
function isError(value) {
|
||||
var signature = Object.prototype.toString.call(value);
|
||||
// [object XXXError]
|
||||
return signature.substr(-6, 5) === 'Error' ||
|
||||
(typeof value.message == 'string' && typeof value.name == 'string');
|
||||
function isNil (value) {
|
||||
return value === null || value === undefined
|
||||
}
|
||||
|
||||
function isArray (value) {
|
||||
// be compatible with IE 8
|
||||
return toStr.call(value) === '[object Array]'
|
||||
}
|
||||
|
||||
function isError (value) {
|
||||
var signature = Object.prototype.toString.call(value)
|
||||
// [object XXXError]
|
||||
return signature.substr(-6, 5) === 'Error' ||
|
||||
(typeof value.message === 'string' && typeof value.name === 'string')
|
||||
}
|
||||
|
||||
/*
|
||||
* Iterates over own enumerable string keyed properties of an object and invokes iteratee for each property.
|
||||
* The iteratee is invoked with three arguments: (value, key, object).
|
||||
* Iterates over own enumerable string keyed properties of an object and invokes iteratee for each property.
|
||||
* The iteratee is invoked with three arguments: (value, key, object).
|
||||
* Iteratee functions may exit iteration early by explicitly returning false.
|
||||
* @param {Object} object The object to iterate over.
|
||||
* @param {Function} iteratee The function invoked per iteration.
|
||||
* @return {Object} Returns object.
|
||||
*/
|
||||
function forOwn(object, iteratee) {
|
||||
object = object || {};
|
||||
for (var k in object) {
|
||||
if (object.hasOwnProperty(k)) {
|
||||
if (iteratee(object[k], k, object) === false) break;
|
||||
}
|
||||
function forOwn (object, iteratee) {
|
||||
object = object || {}
|
||||
for (var k in object) {
|
||||
if (object.hasOwnProperty(k)) {
|
||||
if (iteratee(object[k], k, object) === false) break
|
||||
}
|
||||
return object;
|
||||
}
|
||||
return object
|
||||
}
|
||||
|
||||
/*
|
||||
* Assigns own enumerable string keyed properties of source objects to the destination object.
|
||||
* Source objects are applied from left to right.
|
||||
* Subsequent sources overwrite property assignments of previous sources.
|
||||
* Assigns own enumerable string keyed properties of source objects to the destination object.
|
||||
* Source objects are applied from left to right.
|
||||
* Subsequent sources overwrite property assignments of previous sources.
|
||||
*
|
||||
* Note: This method mutates object and is loosely based on Object.assign.
|
||||
*
|
||||
@@ -43,89 +54,84 @@ function forOwn(object, iteratee) {
|
||||
* @param {...Object} sources The source objects.
|
||||
* @return {Object} Returns object.
|
||||
*/
|
||||
function assign(object) {
|
||||
object = isObject(object) ? object : {};
|
||||
var srcs = Array.prototype.slice.call(arguments, 1);
|
||||
srcs.forEach(function(src) {
|
||||
_assignBinary(object, src);
|
||||
});
|
||||
return object;
|
||||
function assign (object) {
|
||||
object = isObject(object) ? object : {}
|
||||
var srcs = Array.prototype.slice.call(arguments, 1)
|
||||
srcs.forEach(function (src) {
|
||||
_assignBinary(object, src)
|
||||
})
|
||||
return object
|
||||
}
|
||||
|
||||
function _assignBinary(dst, src) {
|
||||
if (!dst) return dst;
|
||||
forOwn(src, function(v, k) {
|
||||
dst[k] = v;
|
||||
});
|
||||
return dst;
|
||||
function _assignBinary (dst, src) {
|
||||
forOwn(src, function (v, k) {
|
||||
dst[k] = v
|
||||
})
|
||||
return dst
|
||||
}
|
||||
|
||||
|
||||
function isArray(value) {
|
||||
return value instanceof Array;
|
||||
function last (arr) {
|
||||
return arr[arr.length - 1]
|
||||
}
|
||||
|
||||
function echo(prefix) {
|
||||
return v => {
|
||||
console.log('[' + prefix + ']', v);
|
||||
return v;
|
||||
};
|
||||
}
|
||||
|
||||
function uniq(arr) {
|
||||
var u = {},
|
||||
a = [];
|
||||
for (var i = 0, l = arr.length; i < l; ++i) {
|
||||
if (u.hasOwnProperty(arr[i])) {
|
||||
continue;
|
||||
}
|
||||
a.push(arr[i]);
|
||||
u[arr[i]] = 1;
|
||||
function uniq (arr) {
|
||||
var u = {}
|
||||
var a = []
|
||||
for (var i = 0, l = arr.length; i < l; ++i) {
|
||||
if (u.hasOwnProperty(arr[i])) {
|
||||
continue
|
||||
}
|
||||
return a;
|
||||
a.push(arr[i])
|
||||
u[arr[i]] = 1
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
/*
|
||||
* Checks if value is the language type of Object.
|
||||
* Checks if value is the language type of Object.
|
||||
* (e.g. arrays, functions, objects, regexes, new Number(0), and new String(''))
|
||||
* @param {any} value The value to check.
|
||||
* @return {Boolean} Returns true if value is an object, else false.
|
||||
*/
|
||||
function isObject(value) {
|
||||
return value !== null && typeof value === 'object';
|
||||
function isObject (value) {
|
||||
var type = typeof value
|
||||
return value != null && (type === 'object' || type === 'function')
|
||||
}
|
||||
|
||||
/*
|
||||
* A function to create flexibly-numbered lists of integers,
|
||||
* handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1.
|
||||
* Returns a list of integers from start (inclusive) to stop (exclusive),
|
||||
* incremented (or decremented) by step, exclusive.
|
||||
* Note that ranges that stop before they start are considered to be zero-length instead of
|
||||
* A function to create flexibly-numbered lists of integers,
|
||||
* handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1.
|
||||
* Returns a list of integers from start (inclusive) to stop (exclusive),
|
||||
* incremented (or decremented) by step, exclusive.
|
||||
* Note that ranges that stop before they start are considered to be zero-length instead of
|
||||
* negative — if you'd like a negative range, use a negative step.
|
||||
*/
|
||||
function range(start, stop, step) {
|
||||
if (arguments.length === 1) {
|
||||
stop = start;
|
||||
start = 0;
|
||||
}
|
||||
step = step || 1;
|
||||
function range (start, stop, step) {
|
||||
if (arguments.length === 1) {
|
||||
stop = start
|
||||
start = 0
|
||||
}
|
||||
step = step || 1
|
||||
|
||||
var arr = [];
|
||||
for (var i = start; i < stop; i += step) {
|
||||
arr.push(i);
|
||||
}
|
||||
return arr;
|
||||
var arr = []
|
||||
for (var i = start; i < stop; i += step) {
|
||||
arr.push(i)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
exports.isString = isString;
|
||||
exports.isArray = isArray;
|
||||
exports.isObject = isObject;
|
||||
exports.isError = isError;
|
||||
// lang
|
||||
exports.isString = isString
|
||||
exports.isObject = isObject
|
||||
exports.isArray = isArray
|
||||
exports.isNil = isNil
|
||||
exports.isError = isError
|
||||
|
||||
exports.range = range;
|
||||
// array
|
||||
exports.range = range
|
||||
exports.last = last
|
||||
|
||||
exports.forOwn = forOwn;
|
||||
exports.assign = assign;
|
||||
exports.uniq = uniq;
|
||||
|
||||
exports.echo = echo;
|
||||
// object
|
||||
exports.forOwn = forOwn
|
||||
exports.assign = assign
|
||||
exports.uniq = uniq
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
const resolve = require('resolve-url')
|
||||
const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/
|
||||
const urlRe = /^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[:?\d]*)\S*$/
|
||||
|
||||
// https://github.com/jinder/path/blob/master/path.js#L567
|
||||
exports.extname = function (path) {
|
||||
return splitPathRe.exec(path).slice(1)[3]
|
||||
}
|
||||
|
||||
// https://www.npmjs.com/package/is-url
|
||||
exports.valid = function (path) {
|
||||
return urlRe.test(path)
|
||||
}
|
||||
|
||||
exports.resolve = function (root, path) {
|
||||
if (Object.prototype.toString.call(root) === '[object Array]') {
|
||||
root = root[0]
|
||||
}
|
||||
if (root && root.charAt(root.length - 1) !== '/') {
|
||||
root += '/'
|
||||
}
|
||||
return resolve(root, path)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
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
|
||||
|
||||
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
|
||||
+18
-21
@@ -1,22 +1,19 @@
|
||||
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 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('')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+27
-29
@@ -1,32 +1,30 @@
|
||||
const Liquid = require('..');
|
||||
const lexical = Liquid.lexical;
|
||||
const re = new RegExp(`(${lexical.identifier.source})`);
|
||||
const assert = require('../src/util/assert.js');
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const re = new RegExp(`(${lexical.identifier.source})`)
|
||||
const assert = require('../src/util/assert.js')
|
||||
|
||||
module.exports = function(liquid) {
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('capture', {
|
||||
parse: function (tagToken, remainTokens) {
|
||||
var match = tagToken.args.match(re)
|
||||
assert(match, `${tagToken.args} not valid identifier`)
|
||||
|
||||
liquid.registerTag('capture', {
|
||||
parse: function(tagToken, remainTokens) {
|
||||
var match = tagToken.args.match(re);
|
||||
assert(match, `${tagToken.args} not valid identifier`);
|
||||
this.variable = match[1]
|
||||
this.templates = []
|
||||
|
||||
this.variable = match[1];
|
||||
this.templates = [];
|
||||
|
||||
var stream = liquid.parser.parseStream(remainTokens);
|
||||
stream.on('tag:endcapture', token => stream.stop())
|
||||
.on('template', tpl => this.templates.push(tpl))
|
||||
.on('end', x => {
|
||||
throw new Error(`tag ${tagToken.raw} not closed`);
|
||||
});
|
||||
stream.start();
|
||||
},
|
||||
render: function(scope, hash) {
|
||||
return liquid.renderer.renderTemplates(this.templates, scope)
|
||||
.then((html) => {
|
||||
scope.set(this.variable, html);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
};
|
||||
var stream = liquid.parser.parseStream(remainTokens)
|
||||
stream.on('tag:endcapture', token => stream.stop())
|
||||
.on('template', tpl => this.templates.push(tpl))
|
||||
.on('end', x => {
|
||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||
})
|
||||
stream.start()
|
||||
},
|
||||
render: function (scope, hash) {
|
||||
return liquid.renderer.renderTemplates(this.templates, scope)
|
||||
.then((html) => {
|
||||
scope.set(this.variable, html)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+35
-39
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+15
-17
@@ -1,17 +1,15 @@
|
||||
module.exports = function(liquid) {
|
||||
|
||||
liquid.registerTag('comment', {
|
||||
parse: function(tagToken, remainTokens) {
|
||||
var stream = liquid.parser.parseStream(remainTokens);
|
||||
stream
|
||||
.on('token', token => {
|
||||
if(token.name === 'endcomment') stream.stop();
|
||||
})
|
||||
.on('end', x => {
|
||||
throw new Error(`tag ${tagToken.raw} not closed`);
|
||||
});
|
||||
stream.start();
|
||||
}
|
||||
});
|
||||
|
||||
};
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('comment', {
|
||||
parse: function (tagToken, remainTokens) {
|
||||
var stream = liquid.parser.parseStream(remainTokens)
|
||||
stream
|
||||
.on('token', token => {
|
||||
if (token.name === 'endcomment') stream.stop()
|
||||
})
|
||||
.on('end', x => {
|
||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||
})
|
||||
stream.start()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+33
-34
@@ -1,44 +1,43 @@
|
||||
const Liquid = require('..');
|
||||
const Promise = require('any-promise');
|
||||
const lexical = Liquid.lexical;
|
||||
const groupRE = new RegExp(`^(?:(${lexical.value.source})\\s*:\\s*)?(.*)$`);
|
||||
const candidatesRE = new RegExp(lexical.value.source, 'g');
|
||||
const assert = require('../src/util/assert.js');
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const groupRE = new RegExp(`^(?:(${lexical.value.source})\\s*:\\s*)?(.*)$`)
|
||||
const candidatesRE = new RegExp(lexical.value.source, 'g')
|
||||
const assert = require('../src/util/assert.js')
|
||||
|
||||
module.exports = function(liquid) {
|
||||
liquid.registerTag('cycle', {
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('cycle', {
|
||||
|
||||
parse: function(tagToken, remainTokens) {
|
||||
var match = groupRE.exec(tagToken.args);
|
||||
assert(match, `illegal tag: ${tagToken.raw}`);
|
||||
parse: function (tagToken, remainTokens) {
|
||||
var match = groupRE.exec(tagToken.args)
|
||||
assert(match, `illegal tag: ${tagToken.raw}`)
|
||||
|
||||
this.group = match[1] || '';
|
||||
var candidates = match[2];
|
||||
this.group = match[1] || ''
|
||||
var candidates = match[2]
|
||||
|
||||
this.candidates = [];
|
||||
this.candidates = []
|
||||
|
||||
while(match = candidatesRE.exec(candidates)){
|
||||
this.candidates.push(match[0]);
|
||||
}
|
||||
while ((match = candidatesRE.exec(candidates))) {
|
||||
this.candidates.push(match[0])
|
||||
}
|
||||
assert(this.candidates.length, `empty candidates: ${tagToken.raw}`)
|
||||
},
|
||||
|
||||
assert(this.candidates.length, `empty candidates: ${tagToken.raw}`);
|
||||
},
|
||||
render: function (scope, hash) {
|
||||
var group = Liquid.evalValue(this.group, scope)
|
||||
var fingerprint = `cycle:${group}:` + this.candidates.join(',')
|
||||
|
||||
render: function(scope, hash) {
|
||||
var group = Liquid.evalValue(this.group, scope);
|
||||
var fingerprint = `cycle:${group}:` + this.candidates.join(',');
|
||||
var register = scope.get('liquid');
|
||||
var idx = register[fingerprint];
|
||||
var groups = scope.opts.groups = scope.opts.groups || {}
|
||||
var idx = groups[fingerprint]
|
||||
|
||||
if(idx === undefined){
|
||||
idx = register[fingerprint] = 0;
|
||||
}
|
||||
if (idx === undefined) {
|
||||
idx = groups[fingerprint] = 0
|
||||
}
|
||||
|
||||
var candidate = this.candidates[idx];
|
||||
idx = (idx + 1) % this.candidates.length;
|
||||
register[fingerprint] = idx;
|
||||
var candidate = this.candidates[idx]
|
||||
idx = (idx + 1) % this.candidates.length
|
||||
groups[fingerprint] = idx
|
||||
|
||||
return Promise.resolve(Liquid.evalValue(candidate, scope));
|
||||
}
|
||||
});
|
||||
};
|
||||
return Promise.resolve(Liquid.evalValue(candidate, scope))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+17
-19
@@ -1,20 +1,18 @@
|
||||
const Liquid = require('..');
|
||||
const lexical = Liquid.lexical;
|
||||
const assert = require('../src/util/assert.js');
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const assert = require('../src/util/assert.js')
|
||||
|
||||
module.exports = function(liquid) {
|
||||
|
||||
liquid.registerTag('decrement', {
|
||||
parse: function(token) {
|
||||
var match = token.args.match(lexical.identifier);
|
||||
assert(match, `illegal identifier ${token.args}`);
|
||||
this.variable = match[0];
|
||||
},
|
||||
render: function(scope, hash) {
|
||||
var v = scope.get(this.variable);
|
||||
if (typeof v !== 'number') v = 0;
|
||||
scope.set(this.variable, v - 1);
|
||||
}
|
||||
});
|
||||
|
||||
};
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('decrement', {
|
||||
parse: function (token) {
|
||||
var match = token.args.match(lexical.identifier)
|
||||
assert(match, `illegal identifier ${token.args}`)
|
||||
this.variable = match[0]
|
||||
},
|
||||
render: function (scope, hash) {
|
||||
var v = scope.get(this.variable)
|
||||
if (typeof v !== 'number') v = 0
|
||||
scope.set(this.variable, v - 1)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+85
-77
@@ -1,88 +1,96 @@
|
||||
const Liquid = require('..');
|
||||
const lexical = Liquid.lexical;
|
||||
const mapSeries = require('../src/util/promise.js').mapSeries;
|
||||
const RenderBreakError = Liquid.Types.RenderBreakError;
|
||||
const assert = require('../src/util/assert.js');
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const mapSeries = require('../src/util/promise.js').mapSeries
|
||||
const _ = require('../src/util/underscore.js')
|
||||
const RenderBreakError = Liquid.Types.RenderBreakError
|
||||
const assert = require('../src/util/assert.js')
|
||||
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
|
||||
`(${lexical.value.source})` +
|
||||
`(?:\\s+${lexical.hash.source})*` +
|
||||
`(?:\\s+(reversed))?$`);
|
||||
`(?:\\s+(reversed))?` +
|
||||
`(?:\\s+${lexical.hash.source})*$`)
|
||||
|
||||
module.exports = function(liquid) {
|
||||
liquid.registerTag('for', {
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('for', {
|
||||
|
||||
parse: function(tagToken, remainTokens) {
|
||||
var match = re.exec(tagToken.args);
|
||||
assert(match, `illegal tag: ${tagToken.raw}`);
|
||||
this.variable = match[1];
|
||||
this.collection = match[2];
|
||||
this.reversed = !!match[3];
|
||||
parse: function (tagToken, remainTokens) {
|
||||
var match = re.exec(tagToken.args)
|
||||
assert(match, `illegal tag: ${tagToken.raw}`)
|
||||
this.variable = match[1]
|
||||
this.collection = match[2]
|
||||
this.reversed = !!match[3]
|
||||
|
||||
this.templates = [];
|
||||
this.elseTemplates = [];
|
||||
this.templates = []
|
||||
this.elseTemplates = []
|
||||
|
||||
var p, stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('start', () => p = this.templates)
|
||||
.on('tag:else', () => p = this.elseTemplates)
|
||||
.on('tag:endfor', () => stream.stop())
|
||||
.on('template', tpl => p.push(tpl))
|
||||
.on('end', () => {
|
||||
throw new Error(`tag ${tagToken.raw} not closed`);
|
||||
});
|
||||
var p
|
||||
var stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('start', () => (p = this.templates))
|
||||
.on('tag:else', () => (p = this.elseTemplates))
|
||||
.on('tag:endfor', () => stream.stop())
|
||||
.on('template', tpl => p.push(tpl))
|
||||
.on('end', () => {
|
||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||
})
|
||||
|
||||
stream.start();
|
||||
},
|
||||
stream.start()
|
||||
},
|
||||
|
||||
render: function(scope, hash) {
|
||||
var collection = Liquid.evalExp(this.collection, scope);
|
||||
if (Liquid.isFalsy(collection)) {
|
||||
return liquid.renderer.renderTemplates(this.elseTemplates, scope);
|
||||
}
|
||||
render: function (scope, hash) {
|
||||
var collection = Liquid.evalExp(this.collection, scope)
|
||||
|
||||
var length = collection.length;
|
||||
var offset = hash.offset || 0;
|
||||
var limit = (hash.limit === undefined) ? collection.length : hash.limit;
|
||||
|
||||
collection = collection.slice(offset, offset + limit);
|
||||
if (this.reversed) collection.reverse();
|
||||
|
||||
var contexts = collection.map((item, i) => {
|
||||
var ctx = {};
|
||||
ctx[this.variable] = item;
|
||||
ctx.forloop = {
|
||||
first: i === 0,
|
||||
index: i + 1,
|
||||
index0: i,
|
||||
last: i === length - 1,
|
||||
length: length,
|
||||
rindex: length - i,
|
||||
rindex0: length - i - 1,
|
||||
stop: false,
|
||||
skip: false
|
||||
};
|
||||
return ctx;
|
||||
});
|
||||
|
||||
var html = '';
|
||||
return mapSeries(contexts, (context) => {
|
||||
scope.push(context);
|
||||
return liquid.renderer
|
||||
.renderTemplates(this.templates, scope)
|
||||
.then(partial => html += partial)
|
||||
.catch(e => {
|
||||
if (e instanceof RenderBreakError) {
|
||||
html += e.resolvedHTML;
|
||||
if (e.message === 'continue') return;
|
||||
}
|
||||
throw e;
|
||||
})
|
||||
.then(() => scope.pop());
|
||||
}).catch((e) => {
|
||||
if (e instanceof RenderBreakError && e.message === 'break') {
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}).then(() => html);
|
||||
if (!Array.isArray(collection)) {
|
||||
if (_.isString(collection) && collection.length > 0) {
|
||||
collection = [collection]
|
||||
} else if (_.isObject(collection)) {
|
||||
collection = Object.keys(collection).map((key) => [key, collection[key]])
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
if (!Array.isArray(collection) || !collection.length) {
|
||||
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
||||
}
|
||||
|
||||
var offset = hash.offset || 0
|
||||
var limit = (hash.limit === undefined) ? collection.length : hash.limit
|
||||
|
||||
collection = collection.slice(offset, offset + limit)
|
||||
if (this.reversed) collection.reverse()
|
||||
|
||||
var contexts = collection.map((item, i) => {
|
||||
var ctx = {}
|
||||
ctx[this.variable] = item
|
||||
ctx.forloop = {
|
||||
first: i === 0,
|
||||
index: i + 1,
|
||||
index0: i,
|
||||
last: i === collection.length - 1,
|
||||
length: collection.length,
|
||||
rindex: collection.length - i,
|
||||
rindex0: collection.length - i - 1
|
||||
}
|
||||
return ctx
|
||||
})
|
||||
|
||||
var html = ''
|
||||
return mapSeries(contexts, (context) => {
|
||||
return Promise.resolve()
|
||||
.then(() => scope.push(context))
|
||||
.then(() => liquid.renderer.renderTemplates(this.templates, scope))
|
||||
.then(partial => (html += partial))
|
||||
.catch(e => {
|
||||
if (e instanceof RenderBreakError) {
|
||||
html += e.resolvedHTML
|
||||
if (e.message === 'continue') return
|
||||
}
|
||||
throw e
|
||||
})
|
||||
.then(() => scope.pop())
|
||||
}).catch((e) => {
|
||||
if (e instanceof RenderBreakError && e.message === 'break') {
|
||||
return
|
||||
}
|
||||
throw e
|
||||
}).then(() => html)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+37
-40
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+47
-37
@@ -1,42 +1,52 @@
|
||||
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 staticFileRE = /[^\s,]+/
|
||||
const assert = require('../src/util/assert.js')
|
||||
|
||||
module.exports = function(liquid) {
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('include', {
|
||||
parse: function (token) {
|
||||
var match = staticFileRE.exec(token.args)
|
||||
if (match) {
|
||||
this.staticValue = 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 = lexical.value.exec(token.args)
|
||||
if (match) {
|
||||
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 = scope.opts.dynamicPartials
|
||||
? Liquid.evalValue(this.value, scope)
|
||||
: this.staticValue
|
||||
assert(filepath, `cannot include with empty filename`)
|
||||
|
||||
var register = scope.get('liquid');
|
||||
var originBlocks = register.blocks;
|
||||
register.blocks = {};
|
||||
var originBlocks = scope.opts.blocks
|
||||
var originBlockMode = scope.opts.blockMode
|
||||
scope.opts.blocks = {}
|
||||
scope.opts.blockMode = 'output'
|
||||
|
||||
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, scope.opts.root)
|
||||
.then((templates) => {
|
||||
scope.push(hash)
|
||||
return liquid.renderer.renderTemplates(templates, scope)
|
||||
})
|
||||
.then((html) => {
|
||||
scope.pop()
|
||||
scope.opts.blocks = originBlocks
|
||||
scope.opts.blockMode = originBlockMode
|
||||
return html
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+17
-19
@@ -1,20 +1,18 @@
|
||||
const Liquid = require('..');
|
||||
const assert = require('../src/util/assert.js');
|
||||
const lexical = Liquid.lexical;
|
||||
const Liquid = require('..')
|
||||
const assert = require('../src/util/assert.js')
|
||||
const lexical = Liquid.lexical
|
||||
|
||||
module.exports = function(liquid) {
|
||||
|
||||
liquid.registerTag('increment', {
|
||||
parse: function(token) {
|
||||
var match = token.args.match(lexical.identifier);
|
||||
assert(match, `illegal identifier ${token.args}`);
|
||||
this.variable = match[0];
|
||||
},
|
||||
render: function(scope, hash) {
|
||||
var v = scope.get(this.variable);
|
||||
if (typeof v !== 'number') v = 0;
|
||||
scope.set(this.variable, v + 1);
|
||||
}
|
||||
});
|
||||
|
||||
};
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('increment', {
|
||||
parse: function (token) {
|
||||
var match = token.args.match(lexical.identifier)
|
||||
assert(match, `illegal identifier ${token.args}`)
|
||||
this.variable = match[0]
|
||||
},
|
||||
render: function (scope, hash) {
|
||||
var v = scope.get(this.variable)
|
||||
if (typeof v !== 'number') v = 0
|
||||
scope.set(this.variable, v + 1)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+16
-16
@@ -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)
|
||||
}
|
||||
|
||||
+77
-59
@@ -1,66 +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 lexical = Liquid.lexical
|
||||
const assert = require('../src/util/assert.js')
|
||||
const staticFileRE = /\S+/
|
||||
|
||||
module.exports = function(liquid) {
|
||||
/*
|
||||
* blockMode:
|
||||
* * "store": store rendered html into blocks
|
||||
* * "output": output rendered html
|
||||
*/
|
||||
|
||||
liquid.registerTag('layout', {
|
||||
parse: function(token, remainTokens){
|
||||
var match = lexical.value.exec(token.args);
|
||||
assert(match, `illegal token ${token.raw}`);
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('layout', {
|
||||
parse: function (token, remainTokens) {
|
||||
var match = staticFileRE.exec(token.args)
|
||||
if (match) {
|
||||
this.staticLayout = match[0]
|
||||
}
|
||||
|
||||
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');
|
||||
match = lexical.value.exec(token.args)
|
||||
if (match) {
|
||||
this.layout = match[0]
|
||||
}
|
||||
|
||||
// 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));
|
||||
}
|
||||
});
|
||||
this.tpls = liquid.parser.parse(remainTokens)
|
||||
},
|
||||
render: function (scope, hash) {
|
||||
var layout = scope.opts.dynamicPartials ? Liquid.evalValue(this.layout, scope) : this.staticLayout
|
||||
assert(layout, `cannot apply layout with empty filename`)
|
||||
|
||||
liquid.registerTag('block', {
|
||||
parse: function(token, remainTokens){
|
||||
var match = /\w+/.exec(token.args);
|
||||
this.block = match ? match[0] : 'anonymous';
|
||||
// render the remaining tokens immediately
|
||||
scope.opts.blockMode = 'store'
|
||||
return liquid.renderer.renderTemplates(this.tpls, scope)
|
||||
.then(html => {
|
||||
if (scope.opts.blocks[''] === undefined) {
|
||||
scope.opts.blocks[''] = html
|
||||
}
|
||||
return liquid.getTemplate(layout, scope.opts.root)
|
||||
})
|
||||
.then(templates => {
|
||||
// push the hash
|
||||
scope.push(hash)
|
||||
scope.opts.blockMode = 'output'
|
||||
return liquid.renderer.renderTemplates(templates, scope)
|
||||
})
|
||||
// pop the hash
|
||||
.then(partial => {
|
||||
scope.pop()
|
||||
return partial
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
liquid.registerTag('block', {
|
||||
parse: function (token, remainTokens) {
|
||||
var match = /\w+/.exec(token.args)
|
||||
this.block = match ? match[0] : ''
|
||||
|
||||
};
|
||||
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) {
|
||||
return Promise.resolve(scope.opts.blocks[this.block])
|
||||
.then(html => html === undefined
|
||||
// render default block
|
||||
? liquid.renderer.renderTemplates(this.tpls, scope)
|
||||
// use child-defined block
|
||||
: html)
|
||||
.then(html => {
|
||||
if (scope.opts.blockMode === 'store') {
|
||||
scope.opts.blocks[this.block] = html
|
||||
return ''
|
||||
}
|
||||
return html
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+21
-25
@@ -1,26 +1,22 @@
|
||||
const Promise = require('any-promise');
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('raw', {
|
||||
parse: function (tagToken, remainTokens) {
|
||||
this.tokens = []
|
||||
|
||||
module.exports = function(liquid) {
|
||||
|
||||
liquid.registerTag('raw', {
|
||||
parse: function(tagToken, remainTokens) {
|
||||
this.tokens = [];
|
||||
|
||||
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`);
|
||||
});
|
||||
stream.start();
|
||||
},
|
||||
render: function(scope, hash) {
|
||||
var tokens = this.tokens.map(token => token.raw).join('');
|
||||
return Promise.resolve(tokens);
|
||||
}
|
||||
});
|
||||
|
||||
};
|
||||
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`)
|
||||
})
|
||||
stream.start()
|
||||
},
|
||||
render: function (scope, hash) {
|
||||
var tokens = this.tokens.map(token => token.raw).join('')
|
||||
return Promise.resolve(tokens)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+71
-83
@@ -1,95 +1,83 @@
|
||||
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 = ''
|
||||
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
|
||||
|
||||
// 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)
|
||||
if (!cols) cols = collection.length
|
||||
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>'
|
||||
}
|
||||
return html
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+28
-27
@@ -1,30 +1,31 @@
|
||||
const Liquid = require('..');
|
||||
const Liquid = require('..')
|
||||
|
||||
module.exports = function(liquid) {
|
||||
liquid.registerTag('unless', {
|
||||
parse: function(tagToken, remainTokens) {
|
||||
this.templates = [];
|
||||
this.elseTemplates = [];
|
||||
var p, stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('start', x => {
|
||||
p = this.templates;
|
||||
this.cond = tagToken.args;
|
||||
})
|
||||
.on('tag:else', token => p = this.elseTemplates)
|
||||
.on('tag:endunless', token => stream.stop())
|
||||
.on('template', tpl => p.push(tpl))
|
||||
.on('end', x => {
|
||||
throw new Error(`tag ${tagToken.raw} not closed`);
|
||||
});
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('unless', {
|
||||
parse: function (tagToken, remainTokens) {
|
||||
this.templates = []
|
||||
this.elseTemplates = []
|
||||
var p
|
||||
var stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('start', x => {
|
||||
p = this.templates
|
||||
this.cond = tagToken.args
|
||||
})
|
||||
.on('tag:else', () => (p = this.elseTemplates))
|
||||
.on('tag:endunless', 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) {
|
||||
var cond = Liquid.evalExp(this.cond, scope);
|
||||
return Liquid.isFalsy(cond) ?
|
||||
liquid.renderer.renderTemplates(this.templates, scope) :
|
||||
liquid.renderer.renderTemplates(this.elseTemplates, scope);
|
||||
}
|
||||
});
|
||||
};
|
||||
render: function (scope, hash) {
|
||||
var cond = Liquid.evalExp(this.cond, scope)
|
||||
return Liquid.isFalsy(cond)
|
||||
? liquid.renderer.renderTemplates(this.templates, scope)
|
||||
: liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"rules": {
|
||||
"no-unused-expressions": "off"
|
||||
},
|
||||
"env": {
|
||||
"mocha": true
|
||||
},
|
||||
"plugins": [
|
||||
"mocha"
|
||||
]
|
||||
}
|
||||
+89
-89
@@ -1,94 +1,94 @@
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
const mock = require('mock-fs');
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const Liquid = require('..');
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
const mock = require('mock-fs')
|
||||
const request = require('supertest')
|
||||
const express = require('express')
|
||||
const Liquid = require('..')
|
||||
|
||||
describe('engine#express()', function() {
|
||||
var app, engine;
|
||||
describe('engine#express()', function () {
|
||||
var app, engine
|
||||
|
||||
beforeEach(function() {
|
||||
app = express();
|
||||
engine = Liquid({
|
||||
root: '/root',
|
||||
extname: '.html'
|
||||
});
|
||||
beforeEach(function () {
|
||||
app = express()
|
||||
engine = Liquid({
|
||||
root: '/root',
|
||||
extname: '.html'
|
||||
})
|
||||
|
||||
app.set('view engine', 'html');
|
||||
app.engine('html', engine.express());
|
||||
app.set('view engine', 'html')
|
||||
app.engine('html', engine.express())
|
||||
|
||||
app.get('/name', (req, res) => res.render('name', {
|
||||
name: 'harttle'
|
||||
}));
|
||||
app.get('/include/:file', (req, res) => res.render('include', {
|
||||
file: req.params.file
|
||||
}));
|
||||
});
|
||||
after(function() {
|
||||
mock.restore();
|
||||
});
|
||||
it('should render express views', function(done) {
|
||||
mock({ '/views/name.html': 'My name is {{name}}.' });
|
||||
app.set('views', ['/views']);
|
||||
request(app).get('/name')
|
||||
.expect('My name is harttle.')
|
||||
.expect(200, done);
|
||||
});
|
||||
it('should pass error when file not found', function(done) {
|
||||
var view = {
|
||||
root: []
|
||||
};
|
||||
var file = '/not-exist.html';
|
||||
var ctx = {};
|
||||
engine.express().call(view, file, ctx, function(err) {
|
||||
try {
|
||||
expect(err.code).to.equal('ENOENT');
|
||||
expect(err.message).to.match(/Failed to lookup/);
|
||||
done();
|
||||
} catch (e) {
|
||||
done(e);
|
||||
}
|
||||
});
|
||||
});
|
||||
it('should respect root option when lookup', function(done) {
|
||||
mock({
|
||||
'/root/foo.html': 'foo',
|
||||
'/views/include.html': '{% include file %}'
|
||||
});
|
||||
app.set('views', ['/views']);
|
||||
request(app).get('/include/foo')
|
||||
.expect('foo')
|
||||
.expect(200, done);
|
||||
});
|
||||
it('should respect express views (Array) when lookup', function(done) {
|
||||
mock({
|
||||
'/views/include.html': '{% include file %}',
|
||||
'/partials/bar.html': 'bar'
|
||||
});
|
||||
app.set('views', ['/views', '/partials']);
|
||||
request(app).get('/include/bar')
|
||||
.expect('bar')
|
||||
.expect(200, done);
|
||||
});
|
||||
it('should respect express views (String) when lookup', function(done) {
|
||||
mock({
|
||||
'/views/include.html': '{% include file %}',
|
||||
'/views/bar.html': 'bar'
|
||||
});
|
||||
app.set('views', '/views');
|
||||
request(app).get('/include/bar')
|
||||
.expect('bar')
|
||||
.expect(200, done);
|
||||
});
|
||||
it('should respect express views (Undefined) when lookup', function(done) {
|
||||
var files = {};
|
||||
files[process.cwd() + '/views/include.html'] = '{% include file %}';
|
||||
files[process.cwd() + '/views/bar.html'] = 'bar';
|
||||
mock(files);
|
||||
app.get('/name', (req, res) => res.render('name', {
|
||||
name: 'harttle'
|
||||
}))
|
||||
app.get('/include/:file', (req, res) => res.render('include', {
|
||||
file: req.params.file
|
||||
}))
|
||||
})
|
||||
after(function () {
|
||||
mock.restore()
|
||||
})
|
||||
it('should render express views', function (done) {
|
||||
mock({ '/views/name.html': 'My name is {{name}}.' })
|
||||
app.set('views', ['/views'])
|
||||
request(app).get('/name')
|
||||
.expect('My name is harttle.')
|
||||
.expect(200, done)
|
||||
})
|
||||
it('should pass error when file not found', function (done) {
|
||||
var view = {
|
||||
root: []
|
||||
}
|
||||
var file = '/not-exist.html'
|
||||
var ctx = {}
|
||||
engine.express().call(view, file, ctx, function (err) {
|
||||
try {
|
||||
expect(err.code).to.equal('ENOENT')
|
||||
expect(err.message).to.match(/Failed to lookup/)
|
||||
done()
|
||||
} catch (e) {
|
||||
done(e)
|
||||
}
|
||||
})
|
||||
})
|
||||
it('should respect root option when lookup', function (done) {
|
||||
mock({
|
||||
'/root/foo.html': 'foo',
|
||||
'/views/include.html': '{% include file %}'
|
||||
})
|
||||
app.set('views', ['/views'])
|
||||
request(app).get('/include/foo')
|
||||
.expect('foo')
|
||||
.expect(200, done)
|
||||
})
|
||||
it('should respect express views (Array) when lookup', function (done) {
|
||||
mock({
|
||||
'/views/include.html': '{% include file %}',
|
||||
'/partials/bar.html': 'bar'
|
||||
})
|
||||
app.set('views', ['/views', '/partials'])
|
||||
request(app).get('/include/bar')
|
||||
.expect('bar')
|
||||
.expect(200, done)
|
||||
})
|
||||
it('should respect express views (String) when lookup', function (done) {
|
||||
mock({
|
||||
'/views/include.html': '{% include file %}',
|
||||
'/views/bar.html': 'bar'
|
||||
})
|
||||
app.set('views', '/views')
|
||||
request(app).get('/include/bar')
|
||||
.expect('bar')
|
||||
.expect(200, done)
|
||||
})
|
||||
it('should respect express views (Undefined) when lookup', function (done) {
|
||||
var files = {}
|
||||
files[process.cwd() + '/views/include.html'] = '{% include file %}'
|
||||
files[process.cwd() + '/views/bar.html'] = 'bar'
|
||||
mock(files)
|
||||
|
||||
request(app).get('/include/bar')
|
||||
.expect('bar')
|
||||
.expect(200, done);
|
||||
});
|
||||
});
|
||||
request(app).get('/include/bar')
|
||||
.expect('bar')
|
||||
.expect(200, done)
|
||||
})
|
||||
})
|
||||
|
||||
+82
-47
@@ -1,57 +1,92 @@
|
||||
const chai = require("chai");
|
||||
const sinon = require("sinon");
|
||||
const sinonChai = require("sinon-chai");
|
||||
const expect = chai.expect;
|
||||
const chai = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const sinonChai = require('sinon-chai')
|
||||
const expect = chai.expect
|
||||
|
||||
chai.use(sinonChai);
|
||||
chai.use(sinonChai)
|
||||
|
||||
var filter = require('../src/filter.js')();
|
||||
var Scope = require('../src/scope.js');
|
||||
var filter = require('../src/filter.js')()
|
||||
var Scope = require('../src/scope.js')
|
||||
|
||||
describe('filter', function() {
|
||||
var scope;
|
||||
beforeEach(function() {
|
||||
filter.clear();
|
||||
scope = Scope.factory();
|
||||
});
|
||||
it('should return default filter when not registered', function() {
|
||||
var result = filter.construct('foo');
|
||||
expect(result.name).to.equal('foo');
|
||||
});
|
||||
describe('filter', function () {
|
||||
var scope
|
||||
beforeEach(function () {
|
||||
filter.clear()
|
||||
scope = Scope.factory()
|
||||
})
|
||||
it('should return default filter when not registered', function () {
|
||||
var result = filter.construct('foo')
|
||||
expect(result.name).to.equal('foo')
|
||||
})
|
||||
|
||||
it('should throw when filter name illegal', function() {
|
||||
expect(function() {
|
||||
filter.construct('/');
|
||||
}).to.throw(/illegal filter/);
|
||||
});
|
||||
it('should throw when filter name illegal', function () {
|
||||
expect(function () {
|
||||
filter.construct('/')
|
||||
}).to.throw(/illegal filter/)
|
||||
})
|
||||
|
||||
it('should parse argument syntax', function() {
|
||||
filter.register('foo', x => x);
|
||||
var f = filter.construct('foo: a, "b"');
|
||||
it('should parse argument syntax', function () {
|
||||
filter.register('foo', x => x)
|
||||
var f = filter.construct('foo: a, "b"')
|
||||
|
||||
expect(f.name).to.equal('foo');
|
||||
expect(f.args).to.deep.equal(['a', '"b"']);
|
||||
});
|
||||
expect(f.name).to.equal('foo')
|
||||
expect(f.args).to.deep.equal(['a', '"b"'])
|
||||
})
|
||||
|
||||
it('should register a simple filter', function() {
|
||||
filter.register('upcase', x => x.toUpperCase());
|
||||
expect(filter.construct('upcase').render('foo', scope)).to.equal('FOO');
|
||||
});
|
||||
it('should register a simple filter', function () {
|
||||
filter.register('upcase', x => x.toUpperCase())
|
||||
expect(filter.construct('upcase').render('foo', scope)).to.equal('FOO')
|
||||
})
|
||||
|
||||
it('should register a argumented filter', function() {
|
||||
filter.register('add', (a, b) => a + b);
|
||||
expect(filter.construct('add: 2').render(3, scope)).to.equal(5);
|
||||
});
|
||||
it('should register a argumented filter', function () {
|
||||
filter.register('add', (a, b) => a + b)
|
||||
expect(filter.construct('add: 2').render(3, scope)).to.equal(5)
|
||||
})
|
||||
|
||||
it('should register a multi-argumented filter', function() {
|
||||
filter.register('add', (a, b, c) => a + b + c);
|
||||
expect(filter.construct('add: 2, "c"').render(3, scope)).to.equal("5c");
|
||||
});
|
||||
it('should register a multi-argumented filter', function () {
|
||||
filter.register('add', (a, b, c) => a + b + c)
|
||||
expect(filter.construct('add: 2, "c"').render(3, scope)).to.equal('5c')
|
||||
})
|
||||
|
||||
it('should call filter with corrct arguments', function() {
|
||||
var spy = sinon.spy();
|
||||
filter.register('foo', spy);
|
||||
filter.construct('foo: 33').render('foo', scope);
|
||||
expect(spy).to.have.been.calledWith('foo', 33);
|
||||
});
|
||||
});
|
||||
it('should call filter with corrct arguments', function () {
|
||||
var spy = sinon.spy()
|
||||
filter.register('foo', spy)
|
||||
filter.construct('foo: 33').render('foo', scope)
|
||||
expect(spy).to.have.been.calledWith('foo', 33)
|
||||
})
|
||||
|
||||
it('should support arguments as named key/values', function () {
|
||||
filter.register('foo', x => x)
|
||||
var f = filter.construct('foo: key1: "literal1", key2: value2')
|
||||
expect(f.name).to.equal('foo')
|
||||
expect(f.args).to.deep.equal([ '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
|
||||
})
|
||||
|
||||
it('should support arguments as named key/values with inline literals', function () {
|
||||
filter.register('foo', x => x)
|
||||
var f = filter.construct('foo: "test0", key1: "literal1", key2: value2')
|
||||
expect(f.name).to.equal('foo')
|
||||
expect(f.args).to.deep.equal([ '"test0"', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
|
||||
})
|
||||
|
||||
it('should support arguments as named key/values with inline values', function () {
|
||||
filter.register('foo', x => x)
|
||||
var f = filter.construct('foo: test0, key1: "literal1", key2: value2')
|
||||
expect(f.name).to.equal('foo')
|
||||
expect(f.args).to.deep.equal([ 'test0', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
|
||||
})
|
||||
|
||||
it('should support argument values named same as keys', function () {
|
||||
filter.register('foo', x => x)
|
||||
var f = filter.construct('foo: a: a')
|
||||
expect(f.name).to.equal('foo')
|
||||
expect(f.args).to.deep.equal(['\'a\'', 'a'])
|
||||
})
|
||||
|
||||
it('should support argument literals named same as keys', function () {
|
||||
filter.register('foo', x => x)
|
||||
var f = filter.construct('foo: a: "a"')
|
||||
expect(f.name).to.equal('foo')
|
||||
expect(f.args).to.deep.equal(['\'a\'', '"a"'])
|
||||
})
|
||||
})
|
||||
|
||||
+355
-258
@@ -1,315 +1,412 @@
|
||||
const chai = require("chai");
|
||||
const chaiAsPromised = require("chai-as-promised");
|
||||
var liquid = require('..')(),
|
||||
ctx;
|
||||
chai.use(chaiAsPromised);
|
||||
const chai = require('chai')
|
||||
const chaiAsPromised = require('chai-as-promised')
|
||||
const expect = chai.expect
|
||||
var liquid = require('..')()
|
||||
chai.use(chaiAsPromised)
|
||||
|
||||
function test(src, dst) {
|
||||
ctx = {
|
||||
date: new Date(),
|
||||
foo: 'bar',
|
||||
arr: [-2, 'a'],
|
||||
obj: {
|
||||
foo: 'bar'
|
||||
},
|
||||
func: function() {},
|
||||
posts: [{
|
||||
category: 'foo'
|
||||
}, {
|
||||
category: 'bar'
|
||||
}]
|
||||
};
|
||||
return liquid.parseAndRender(src, ctx).should.eventually.equal(dst);
|
||||
var ctx = {
|
||||
date: new Date(),
|
||||
foo: 'bar',
|
||||
arr: [-2, 'a'],
|
||||
obj: {
|
||||
foo: 'bar'
|
||||
},
|
||||
func: function () {},
|
||||
posts: [{
|
||||
category: 'foo'
|
||||
}, {
|
||||
category: 'bar'
|
||||
}]
|
||||
}
|
||||
|
||||
describe('filters', function() {
|
||||
describe('abs', function() {
|
||||
it('should return 3 for -3', () => test('{{ -3 | abs }}', '3'));
|
||||
it('should return 2 for arr[0]', () => test('{{ arr[0] | abs }}', '2'));
|
||||
});
|
||||
function test (src, dst) {
|
||||
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
|
||||
}
|
||||
|
||||
describe('append', function() {
|
||||
it('should return "-3abc" for -3, "abc"',
|
||||
() => test('{{ -3 | append: "abc" }}', '-3abc'));
|
||||
it('should return "abar" for "a",foo', () => test('{{ "a" | append: foo }}', 'abar'));
|
||||
});
|
||||
describe('filters', function () {
|
||||
describe('abs', function () {
|
||||
it('should return 3 for -3', () => test('{{ -3 | abs }}', '3'))
|
||||
it('should return 2 for arr[0]', () => test('{{ arr[0] | abs }}', '2'))
|
||||
it('should return convert string', () => test('{{ "-3" | abs }}', '3'))
|
||||
})
|
||||
|
||||
it('should support capitalize', () => test('{{ "i am good" | capitalize }}', 'I am good'));
|
||||
describe('append', function () {
|
||||
it('should return "-3abc" for -3, "abc"',
|
||||
() => test('{{ -3 | append: "abc" }}', '-3abc'))
|
||||
it('should return "abar" for "a",foo', () => test('{{ "a" | append: foo }}', 'abar'))
|
||||
})
|
||||
|
||||
describe('ceil', function() {
|
||||
it('should return "2" for 1.2', () => test('{{ 1.2 | ceil }}', '2'));
|
||||
it('should return "2" for 2.0', () => test('{{ 2.0 | ceil }}', '2'));
|
||||
it('should return "4" for 3.5', () => test('{{ "3.5" | ceil }}', '4'));
|
||||
it('should return "184" for 183.357', () => test('{{ 183.357 | ceil }}', '184'));
|
||||
});
|
||||
it('should support capitalize', () => test('{{ "i am good" | capitalize }}', 'I am good'))
|
||||
|
||||
describe('date', function() {
|
||||
it('should support date: %a %b %d %Y', function() {
|
||||
var str = ctx.date.toDateString();
|
||||
return test('{{ date | date:"%a %b %d %Y"}}', str);
|
||||
});
|
||||
it('should create a new Date when given "now"', function() {
|
||||
return test('{{ "now" | date: "%Y"}}', (new Date).getFullYear().toString());
|
||||
});
|
||||
});
|
||||
describe('ceil', function () {
|
||||
it('should return "2" for 1.2', () => test('{{ 1.2 | ceil }}', '2'))
|
||||
it('should return "2" for 2.0', () => test('{{ 2.0 | ceil }}', '2'))
|
||||
it('should return "4" for 3.5', () => test('{{ "3.5" | ceil }}', '4'))
|
||||
it('should return "184" for 183.357', () => test('{{ 183.357 | ceil }}', '184'))
|
||||
})
|
||||
|
||||
it('should support default', () => test('{{false |default: "a"}}', 'a'));
|
||||
describe('concat', function () {
|
||||
it('should concat arrays', () => test(`
|
||||
{%- assign fruits = "apples, oranges, peaches" | split: ", " -%}
|
||||
{%- assign vegetables = "carrots, turnips, potatoes" | split: ", " -%}
|
||||
|
||||
describe('divided_by', function() {
|
||||
it('should return 2 for 4,2', () => test('{{4 | divided_by: 2}}', '2'));
|
||||
it('should return 4 for 16,4', () => test('{{16 | divided_by: 4}}', '4'));
|
||||
it('should return 1 for 5,3', () => test('{{5 | divided_by: 3}}', '1'));
|
||||
});
|
||||
{%- assign everything = fruits | concat: vegetables -%}
|
||||
|
||||
describe('downcase', function() {
|
||||
it('should return "parker moore" for "Parker Moore"',
|
||||
() => test('{{ "Parker Moore" | downcase }}', 'parker moore'));
|
||||
it('should return "apple" for "apple"',
|
||||
() => test('{{ "apple" | downcase }}', 'apple'));
|
||||
});
|
||||
{%- 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 -%}
|
||||
|
||||
describe('escape', function() {
|
||||
it('should escape \' and &', function() {
|
||||
return test('{{ "Have you read \'James & the Giant Peach\'?" | escape }}',
|
||||
'Have you read 'James & the Giant Peach'?');
|
||||
});
|
||||
it('should escape normal string', function() {
|
||||
return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara');
|
||||
});
|
||||
it('should escape function', function() {
|
||||
return test('{{ func | escape }}', 'function () {}');
|
||||
});
|
||||
});
|
||||
{%- for item in everything -%}
|
||||
- {{ item }}
|
||||
{% endfor -%}`,
|
||||
`- apples
|
||||
- oranges
|
||||
- peaches
|
||||
- carrots
|
||||
- turnips
|
||||
- potatoes
|
||||
- chairs
|
||||
- tables
|
||||
- shelves
|
||||
`))
|
||||
})
|
||||
|
||||
describe('escape_once', function() {
|
||||
it('should do escape', () =>
|
||||
test('{{ "1 < 2 & 3" | escape_once }}', '1 < 2 & 3'));
|
||||
it('should not escape twice',
|
||||
() => test('{{ "1 < 2 & 3" | escape_once }}', '1 < 2 & 3'));
|
||||
});
|
||||
describe('date', function () {
|
||||
it('should support date: %a %b %d %Y', function () {
|
||||
var str = ctx.date.toDateString()
|
||||
return test('{{ date | date:"%a %b %d %Y"}}', str)
|
||||
})
|
||||
it('should create a new Date when given "now"', function () {
|
||||
return test('{{ "now" | date: "%Y"}}', (new Date()).getFullYear().toString())
|
||||
})
|
||||
it('should parse as Date when given UTC string', function () {
|
||||
return test('{{ "1991-02-22T00:00:00" | date: "%Y"}}', '1991')
|
||||
})
|
||||
it('should render string as string if not valid', function () {
|
||||
return test('{{ "foo" | date: "%Y"}}', 'foo')
|
||||
})
|
||||
it('should render object as string if not valid', function () {
|
||||
return test('{{ obj | date: "%Y"}}', '{"foo":"bar"}')
|
||||
})
|
||||
})
|
||||
|
||||
it('should support split/first', function() {
|
||||
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
|
||||
'{{ my_array | first }}';
|
||||
return test(src, 'apples');
|
||||
});
|
||||
describe('default', function () {
|
||||
it('should use default when falsy', () => test('{{false |default: "a"}}', 'a'))
|
||||
it('should not use default when truthy', () => test('{{true |default: "a"}}', 'true'))
|
||||
})
|
||||
|
||||
describe('floor', function() {
|
||||
it('should return "1" for 1.2', () => test('{{ 1.2 | floor }}', '1'));
|
||||
it('should return "2" for 2.0', () => test('{{ 2.0 | floor }}', '2'));
|
||||
it('should return "183" for 183.357', () => test('{{ 183.357 | floor }}', '183'));
|
||||
it('should return "3" for 3.5', () => test('{{ "3.5" | floor }}', '3'));
|
||||
});
|
||||
describe('divided_by', function () {
|
||||
it('should return 2 for 4,2', () => test('{{4 | divided_by: 2}}', '2'))
|
||||
it('should return 4 for 16,4', () => test('{{16 | divided_by: 4}}', '4'))
|
||||
it('should return 1 for 5,3', () => test('{{5 | divided_by: 3}}', (5 / 3).toString()))
|
||||
it('should convert string to number', () => test('{{"6" | divided_by: "3"}}', '2'))
|
||||
})
|
||||
|
||||
it('should support join', function() {
|
||||
var src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
|
||||
'{{ beatles | join: " and " }}';
|
||||
return test(src, 'John and Paul and George and Ringo');
|
||||
});
|
||||
describe('downcase', function () {
|
||||
it('should return "parker moore" for "Parker Moore"',
|
||||
() => test('{{ "Parker Moore" | downcase }}', 'parker moore'))
|
||||
it('should return "apple" for "apple"',
|
||||
() => test('{{ "apple" | downcase }}', 'apple'))
|
||||
})
|
||||
|
||||
it('should support split/last', function() {
|
||||
var src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
|
||||
'{{ my_array|last }}';
|
||||
return test(src, 'tiger');
|
||||
});
|
||||
describe('escape', function () {
|
||||
it('should escape \' and &', function () {
|
||||
return test('{{ "Have you read \'James & the Giant Peach\'?" | escape }}',
|
||||
'Have you read 'James & the Giant Peach'?')
|
||||
})
|
||||
it('should escape normal string', function () {
|
||||
return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara')
|
||||
})
|
||||
it('should escape function', function () {
|
||||
return test('{{ func | escape }}', 'function () {}')
|
||||
})
|
||||
})
|
||||
|
||||
it('should support lstrip', function() {
|
||||
var src = '{{ " So much room for activities! " | lstrip }}';
|
||||
return test(src, 'So much room for activities! ');
|
||||
});
|
||||
describe('escape_once', function () {
|
||||
it('should do escape', () =>
|
||||
test('{{ "1 < 2 & 3" | escape_once }}', '1 < 2 & 3'))
|
||||
it('should not escape twice',
|
||||
() => test('{{ "1 < 2 & 3" | escape_once }}', '1 < 2 & 3'))
|
||||
})
|
||||
|
||||
it('should support map', function() {
|
||||
return test('{{posts | map: "category"}}', '["foo","bar"]');
|
||||
});
|
||||
it('should support split/first', function () {
|
||||
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
|
||||
'{{ my_array | first }}'
|
||||
return test(src, 'apples')
|
||||
})
|
||||
|
||||
describe('minus', function() {
|
||||
it('should return "2" for 4,2', () => test('{{ 4 | minus: 2 }}', '2'));
|
||||
it('should return "12" for 16,4', () => test('{{ 16 | minus: 4 }}', '12'));
|
||||
it('should return "171.357" for 183.357,12',
|
||||
() => test('{{ 183.357 | minus: 12 }}', '171.357'));
|
||||
});
|
||||
describe('floor', function () {
|
||||
it('should return "1" for 1.2', () => test('{{ 1.2 | floor }}', '1'))
|
||||
it('should return "2" for 2.0', () => test('{{ 2.0 | floor }}', '2'))
|
||||
it('should return "183" for 183.357', () => test('{{ 183.357 | floor }}', '183'))
|
||||
it('should return "3" for 3.5', () => test('{{ "3.5" | floor }}', '3'))
|
||||
})
|
||||
|
||||
describe('modulo', function() {
|
||||
it('should return "1" for 3,2', () => test('{{ 3 | modulo: 2 }}', '1'));
|
||||
it('should return "3" for 24,7', () => test('{{ 24 | modulo: 7 }}', '3'));
|
||||
it('should return "3.357" for 183.357,12',
|
||||
() => test('{{ 183.357 | modulo: 12 }}', '3.357'));
|
||||
});
|
||||
it('should support join', function () {
|
||||
var src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
|
||||
'{{ beatles | join: " and " }}'
|
||||
return test(src, 'John and Paul and George and Ringo')
|
||||
})
|
||||
|
||||
it('should support string_with_newlines', function() {
|
||||
var src = '{% capture string_with_newlines %}\n' +
|
||||
it('should support split/last', function () {
|
||||
var src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
|
||||
'{{ my_array|last }}'
|
||||
return test(src, 'tiger')
|
||||
})
|
||||
|
||||
it('should support lstrip', function () {
|
||||
var src = '{{ " So much room for activities! " | lstrip }}'
|
||||
return test(src, 'So much room for activities! ')
|
||||
})
|
||||
|
||||
it('should support map', function () {
|
||||
return test('{{posts | map: "category"}}', '["foo","bar"]')
|
||||
})
|
||||
|
||||
describe('minus', function () {
|
||||
it('should return "2" for 4,2', () => test('{{ 4 | minus: 2 }}', '2'))
|
||||
it('should return "12" for 16,4', () => test('{{ 16 | minus: 4 }}', '12'))
|
||||
it('should return "171.357" for 183.357,12',
|
||||
() => test('{{ 183.357 | minus: 12 }}', '171.357'))
|
||||
it('should convert first arg as number', () => test('{{ "4" | minus: 1 }}', '3'))
|
||||
it('should convert both args as number', () => test('{{ "4" | minus: "1" }}', '3'))
|
||||
})
|
||||
|
||||
describe('modulo', function () {
|
||||
it('should return "1" for 3,2', () => test('{{ 3 | modulo: 2 }}', '1'))
|
||||
it('should return "3" for 24,7', () => test('{{ 24 | modulo: 7 }}', '3'))
|
||||
it('should return "3.357" for 183.357,12',
|
||||
() => test('{{ 183.357 | modulo: 12 }}', '3.357'))
|
||||
it('should convert string', () => test('{{ "24" | modulo: "7" }}', '3'))
|
||||
})
|
||||
|
||||
it('should support string_with_newlines', function () {
|
||||
var src = '{% capture string_with_newlines %}\n' +
|
||||
'Hello\n' +
|
||||
'there\n' +
|
||||
'{% endcapture %}' +
|
||||
'{{ string_with_newlines | newline_to_br }}';
|
||||
var dst = '<br />' +
|
||||
'{{ string_with_newlines | newline_to_br }}'
|
||||
var dst = '<br />' +
|
||||
'Hello<br />' +
|
||||
'there<br />';
|
||||
return test(src, dst);
|
||||
});
|
||||
'there<br />'
|
||||
return test(src, dst)
|
||||
})
|
||||
|
||||
describe('plus', function() {
|
||||
it('should return "6" for 4,2', () => test('{{ 4 | plus: 2 }}', '6'));
|
||||
it('should return "20" for 16,4', () => test('{{ 16 | plus: 4 }}', '20'));
|
||||
it('should return "195.357" for 183.357,12',
|
||||
() => test('{{ 183.357 | plus: 12 }}', '195.357'));
|
||||
});
|
||||
describe('plus', function () {
|
||||
it('should return "6" for 4,2', () => test('{{ 4 | plus: 2 }}', '6'))
|
||||
it('should return "20" for 16,4', () => test('{{ 16 | plus: 4 }}', '20'))
|
||||
it('should return "195.357" for 183.357,12',
|
||||
() => test('{{ 183.357 | plus: 12 }}', '195.357'))
|
||||
it('should convert first arg as number', () => test('{{ "4" | plus: 2 }}', '6'))
|
||||
it('should convert both args as number', () => test('{{ "4" | plus: "2" }}', '6'))
|
||||
})
|
||||
|
||||
it('should support prepend', function() {
|
||||
return test('{% assign url = "liquidmarkup.com" %}' +
|
||||
it('should support prepend', function () {
|
||||
return test('{% assign url = "liquidmarkup.com" %}' +
|
||||
'{{ "/index.html" | prepend: url }}',
|
||||
'liquidmarkup.com/index.html');
|
||||
});
|
||||
'liquidmarkup.com/index.html')
|
||||
})
|
||||
|
||||
it('should support remove', function() {
|
||||
return test('{{ "I strained to see the train through the rain" | remove: "rain" }}',
|
||||
'I sted to see the t through the ');
|
||||
});
|
||||
it('should support remove', function () {
|
||||
return test('{{ "I strained to see the train through the rain" | remove: "rain" }}',
|
||||
'I sted to see the t through the ')
|
||||
})
|
||||
|
||||
it('should support remove_first', function() {
|
||||
return test('{{ "I strained to see the train through the rain" | remove_first: "rain" }}',
|
||||
'I sted to see the train through the rain');
|
||||
});
|
||||
it('should support remove_first', function () {
|
||||
return test('{{ "I strained to see the train through the rain" | remove_first: "rain" }}',
|
||||
'I sted to see the train through the rain')
|
||||
})
|
||||
|
||||
it('should support replace', function() {
|
||||
return test('{{ "Take my protein pills and put my helmet on" | replace: "my", "your" }}',
|
||||
'Take your protein pills and put your helmet on');
|
||||
});
|
||||
it('should support replace', function () {
|
||||
return test('{{ "Take my protein pills and put my helmet on" | replace: "my", "your" }}',
|
||||
'Take your protein pills and put your helmet on')
|
||||
})
|
||||
|
||||
it('should support replace_first', function() {
|
||||
return test('{% assign my_string = "Take my protein pills and put my helmet on" %}\n' +
|
||||
it('should support replace_first', function () {
|
||||
return test('{% assign my_string = "Take my protein pills and put my helmet on" %}\n' +
|
||||
'{{ my_string | replace_first: "my", "your" }}',
|
||||
'\nTake your protein pills and put my helmet on');
|
||||
});
|
||||
'\nTake your protein pills and put my helmet on')
|
||||
})
|
||||
|
||||
it('should support reverse', function() {
|
||||
return test('{{ "Ground control to Major Tom." | split: "" | reverse | join: "" }}',
|
||||
'.moT rojaM ot lortnoc dnuorG');
|
||||
});
|
||||
it('should support reverse', function () {
|
||||
return test('{{ "Ground control to Major Tom." | split: "" | reverse | join: "" }}',
|
||||
'.moT rojaM ot lortnoc dnuorG')
|
||||
})
|
||||
|
||||
describe('round', function() {
|
||||
it('should return "1" for 1.2', () => test('{{1.2|round}}', '1'));
|
||||
it('should return "3" for 2.7', () => test('{{2.7|round}}', '3'));
|
||||
it('should return "183.36" for 183.357,2',
|
||||
() => test('{{183.357|round: 2}}', '183.36'));
|
||||
});
|
||||
describe('round', function () {
|
||||
it('should return "1" for 1.2', () => test('{{1.2|round}}', '1'))
|
||||
it('should return "3" for 2.7', () => test('{{2.7|round}}', '3'))
|
||||
it('should return "183.36" for 183.357,2',
|
||||
() => test('{{183.357|round: 2}}', '183.36'))
|
||||
it('should convert string to number', () => test('{{"2.7"|round}}', '3'))
|
||||
})
|
||||
|
||||
it('should support rstrip', function() {
|
||||
return test('{{ " So much room for activities! " | rstrip }}',
|
||||
' So much room for activities!');
|
||||
});
|
||||
it('should support rstrip', function () {
|
||||
return test('{{ " So much room for activities! " | rstrip }}',
|
||||
' So much room for activities!')
|
||||
})
|
||||
|
||||
describe('size', function() {
|
||||
it('should return string length',
|
||||
() => test('{{ "Ground control to Major Tom." | size }}', '28'));
|
||||
it('should return array size', function() {
|
||||
return test('{% assign my_array = "apples, oranges, peaches, plums"' +
|
||||
describe('size', function () {
|
||||
it('should return string length',
|
||||
() => test('{{ "Ground control to Major Tom." | size }}', '28'))
|
||||
it('should return array size', function () {
|
||||
return test('{% assign my_array = "apples, oranges, peaches, plums"' +
|
||||
' | split: ", " %}{{ my_array | size }}',
|
||||
'4');
|
||||
});
|
||||
});
|
||||
'4')
|
||||
})
|
||||
it('should also be used with dot notation - string',
|
||||
() => test('{% assign my_string = "Ground control to Major Tom." %}{{ my_string.size }}', '28'))
|
||||
it('should also be used with dot notation - array',
|
||||
() => test('{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}{{ my_array.size }}', '4'))
|
||||
})
|
||||
|
||||
describe('slice', function() {
|
||||
it('should slice first char by 0', () => test('{{ "Liquid" | slice: 0 }}', 'L'));
|
||||
it('should slice third char by 2', () => test('{{ "Liquid" | slice: 2 }}', 'q'));
|
||||
it('should slice substr by 2,5', () => test('{{ "Liquid" | slice: 2, 5 }}', 'quid'));
|
||||
it('should slice substr by -3,2', () => test('{{ "Liquid" | slice: -3, 2 }}', 'ui'));
|
||||
});
|
||||
describe('slice', function () {
|
||||
it('should slice first char by 0', () => test('{{ "Liquid" | slice: 0 }}', 'L'))
|
||||
it('should slice third char by 2', () => test('{{ "Liquid" | slice: 2 }}', 'q'))
|
||||
it('should slice substr by 2,5', () => test('{{ "Liquid" | slice: 2, 5 }}', 'quid'))
|
||||
it('should slice substr by -3,2', () => test('{{ "Liquid" | slice: -3, 2 }}', 'ui'))
|
||||
})
|
||||
|
||||
it('should support sort', function() {
|
||||
return test('{% assign my_array = "zebra, octopus, giraffe, Sally Snake"' +
|
||||
it('should support sort', function () {
|
||||
return test('{% assign my_array = "zebra, octopus, giraffe, Sally Snake"' +
|
||||
' | split: ", " %}' +
|
||||
'{{ my_array | sort | join: ", " }}',
|
||||
'Sally Snake, giraffe, octopus, zebra');
|
||||
});
|
||||
'Sally Snake, giraffe, octopus, zebra')
|
||||
})
|
||||
|
||||
it('should support split', function() {
|
||||
return test('{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
|
||||
it('should support split', function () {
|
||||
return test('{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
|
||||
'{% for member in beatles %}' +
|
||||
'{{ member }} ' +
|
||||
'{% endfor %}',
|
||||
'John Paul George Ringo ');
|
||||
});
|
||||
'John Paul George Ringo ')
|
||||
})
|
||||
|
||||
it('should support strip', function() {
|
||||
return test('{{ " So much room for activities! " | strip }}',
|
||||
'So much room for activities!');
|
||||
});
|
||||
it('should support strip', function () {
|
||||
return test('{{ " So much room for activities! " | strip }}',
|
||||
'So much room for activities!')
|
||||
})
|
||||
|
||||
describe('strip_html', function() {
|
||||
it('should strip all tags', function() {
|
||||
return test('{{ "Have <em>you</em> read <strong>Ulysses</strong>?" | strip_html }}',
|
||||
'Have you read Ulysses?');
|
||||
});
|
||||
it('should strip until empty', function() {
|
||||
return test('{{"<br/><br />< p ></p></ p >" | strip_html }}', '');
|
||||
});
|
||||
});
|
||||
describe('strip_html', function () {
|
||||
it('should strip all tags', function () {
|
||||
return test('{{ "Have <em>you</em> read <cite><a href="https://en.wikipedia.org/wiki/Ulysses_(novel)">Ulysses</a></cite>?" | strip_html }}',
|
||||
'Have you read Ulysses?')
|
||||
})
|
||||
it('should strip all comment tags', function () {
|
||||
return test('{{ "<!--Have you read-->Ulysses?" | strip_html }}',
|
||||
'Ulysses?')
|
||||
})
|
||||
it('should strip all style tags and their contents', function () {
|
||||
return test('{{ "<style>cite { font-style: italic; }</style><cite>Ulysses<cite>?" | strip_html }}',
|
||||
'Ulysses?')
|
||||
})
|
||||
it('should strip all scripts tags and their contents', function () {
|
||||
return test('{{ "<script async>console.log(\'hello world\')</script><cite>Ulysses<cite>?" | strip_html }}',
|
||||
'Ulysses?')
|
||||
})
|
||||
it('should strip until empty', function () {
|
||||
return test('{{"<br/><br />< p ></p></ p >" | strip_html }}', '')
|
||||
})
|
||||
})
|
||||
|
||||
it('should support strip_newlines', function() {
|
||||
return test('{% capture string_with_newlines %}\n' +
|
||||
it('should support strip_newlines', function () {
|
||||
return test('{% capture string_with_newlines %}\n' +
|
||||
'Hello\nthere\n{% endcapture %}' +
|
||||
'{{ string_with_newlines | strip_newlines }}',
|
||||
'Hellothere');
|
||||
});
|
||||
'Hellothere')
|
||||
})
|
||||
|
||||
describe('times', function() {
|
||||
it('should return "6" for 3,2', () => test('{{ 3 | times: 2 }}', '6'));
|
||||
it('should return "168" for 24,7', () => test('{{ 24 | times: 7 }}', '168'));
|
||||
it('should return "2200.284" for 183.357,12',
|
||||
() => test('{{ 183.357 | times: 12 }}', '2200.284'));
|
||||
});
|
||||
describe('times', function () {
|
||||
it('should return "6" for 3,2', () => test('{{ 3 | times: 2 }}', '6'))
|
||||
it('should return "168" for 24,7', () => test('{{ 24 | times: 7 }}', '168'))
|
||||
it('should return "2200.284" for 183.357,12',
|
||||
() => test('{{ 183.357 | times: 12 }}', '2200.284'))
|
||||
it('should convert string to number', () => test('{{ "24" | times: "7" }}', '168'))
|
||||
})
|
||||
|
||||
describe('truncate', function() {
|
||||
it('should truncate when string too long', function() {
|
||||
return test('{{ "Ground control to Major Tom." | truncate: 20 }}',
|
||||
'Ground control to...');
|
||||
});
|
||||
it('should not truncate when string not long enough', function() {
|
||||
return test('{{ "Ground control to Major Tom." | truncate: 80 }}',
|
||||
'Ground control to Major Tom.');
|
||||
});
|
||||
it('should truncate with custom ellipsis', function() {
|
||||
return test('{{ "Ground control to Major Tom." | truncate: 25,", and so on" }}',
|
||||
'Ground control, and so on');
|
||||
});
|
||||
it('should truncate with empty custom ellipsis', function() {
|
||||
return test('{{ "Ground control to Major Tom." | truncate: 20, "" }}',
|
||||
'Ground control to Ma');
|
||||
});
|
||||
});
|
||||
describe('truncate', function () {
|
||||
it('should truncate when string too long', function () {
|
||||
return test('{{ "Ground control to Major Tom." | truncate: 20 }}',
|
||||
'Ground control to...')
|
||||
})
|
||||
it('should not truncate when string not long enough', function () {
|
||||
return test('{{ "Ground control to Major Tom." | truncate: 80 }}',
|
||||
'Ground control to Major Tom.')
|
||||
})
|
||||
it('should truncate with custom ellipsis', function () {
|
||||
return test('{{ "Ground control to Major Tom." | truncate: 25,", and so on" }}',
|
||||
'Ground control, and so on')
|
||||
})
|
||||
it('should truncate with empty custom ellipsis', function () {
|
||||
return test('{{ "Ground control to Major Tom." | truncate: 20, "" }}',
|
||||
'Ground control to Ma')
|
||||
})
|
||||
it('should not truncate when short enough', function () {
|
||||
return test('{{ "12345" | truncate: 5 }}', '12345')
|
||||
})
|
||||
it('should default to 16', function () {
|
||||
return test('{{ "1234567890abcdefghi" | truncate }}', '1234567890abc...')
|
||||
})
|
||||
})
|
||||
|
||||
describe('truncatewords', function() {
|
||||
it('should truncate when too many words', function() {
|
||||
return test('{{ "Ground control to Major Tom." | truncatewords: 3 }}',
|
||||
'Ground control to...');
|
||||
});
|
||||
it('should not truncate when not enough words', function() {
|
||||
return test('{{ "Ground control to Major Tom." | truncatewords: 8 }}',
|
||||
'Ground control to Major Tom.');
|
||||
});
|
||||
it('should truncate with custom ellipsis', function() {
|
||||
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "--" }}',
|
||||
'Ground control to--');
|
||||
});
|
||||
it('should truncate with empty custom ellipsis', function() {
|
||||
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "" }}',
|
||||
'Ground control to');
|
||||
});
|
||||
});
|
||||
describe('truncatewords', function () {
|
||||
it('should truncate when too many words', function () {
|
||||
return test('{{ "Ground control to Major Tom." | truncatewords: 3 }}',
|
||||
'Ground control to...')
|
||||
})
|
||||
it('should not truncate when not enough words', function () {
|
||||
return test('{{ "Ground control to Major Tom." | truncatewords: 8 }}',
|
||||
'Ground control to Major Tom.')
|
||||
})
|
||||
it('should truncate with custom ellipsis', function () {
|
||||
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "--" }}',
|
||||
'Ground control to--')
|
||||
})
|
||||
it('should truncate with empty custom ellipsis', function () {
|
||||
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "" }}',
|
||||
'Ground control to')
|
||||
})
|
||||
})
|
||||
|
||||
it('should support uniq', function() {
|
||||
return test('{% assign my_array = "ants, bugs, bees, bugs, ants" | split: ", " %}' +
|
||||
'{{ my_array | uniq | join: ", " }}',
|
||||
'ants, bugs, bees');
|
||||
});
|
||||
describe('uniq', function () {
|
||||
it('should uniq string list', function () {
|
||||
return test(
|
||||
'{% assign my_array = "ants, bugs, bees, bugs, ants" | split: ", " %}' +
|
||||
'{{ my_array | uniq | join: ", " }}',
|
||||
'ants, bugs, bees'
|
||||
)
|
||||
})
|
||||
it('should uniq falsy value', function () {
|
||||
return test('{{"" | uniq | join: ","}}', '')
|
||||
})
|
||||
})
|
||||
|
||||
it('should support upcase', () => test('{{ "Parker Moore" | upcase }}', 'PARKER MOORE'));
|
||||
it('should support upcase', () => test('{{ "Parker Moore" | upcase }}', 'PARKER MOORE'))
|
||||
|
||||
describe('url_encode', function() {
|
||||
it('should encode @',
|
||||
() => test('{{ "[email protected]" | url_encode }}', 'john%40liquid.com'));
|
||||
it('should encode <space>',
|
||||
() => test('{{ "Tetsuro Takara" | url_encode }}', 'Tetsuro%20Takara'));
|
||||
});
|
||||
});
|
||||
describe('url_encode', function () {
|
||||
it('should encode @',
|
||||
() => test('{{ "[email protected]" | url_encode }}', 'john%40liquid.com'))
|
||||
it('should encode <space>',
|
||||
() => test('{{ "Tetsuro Takara" | url_encode }}', 'Tetsuro%20Takara'))
|
||||
})
|
||||
|
||||
describe('obj_test', function () {
|
||||
liquid.registerFilter('obj_test', function () {
|
||||
return Array.prototype.slice.call(arguments).join(',')
|
||||
})
|
||||
it('should support object', () => test(`{{ "a" | obj_test: k1: "v1", k2: foo }}`, 'a,k1,v1,k2,bar'))
|
||||
it('should support mixed object', () => test(`{{ "a" | obj_test: "something", k1: "v1", k2: foo }}`, 'a,something,k1,v1,k2,bar'))
|
||||
})
|
||||
})
|
||||
|
||||
+119
-110
@@ -1,122 +1,131 @@
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
|
||||
var lexical = require('../src/lexical.js');
|
||||
var lexical = require('../src/lexical.js')
|
||||
|
||||
describe('lexical', function() {
|
||||
it('should test filter syntax', function() {
|
||||
lexical.filterLine.test('abs').should.equal(true);
|
||||
lexical.filterLine.test('plus:1').should.equal(true);
|
||||
lexical.filterLine.test('replace: "a", b').should.equal(true);
|
||||
lexical.filterLine.test('foo: a, "b"').should.equal(true);
|
||||
lexical.filterLine.test('abs | another').should.equal(false);
|
||||
lexical.filterLine.test('join: "," | another').should.equal(false);
|
||||
});
|
||||
it('should test boolean literal', function() {
|
||||
lexical.isLiteral('true').should.equal(true);
|
||||
lexical.isLiteral('TrUE').should.equal(true);
|
||||
lexical.isLiteral('false').should.equal(true);
|
||||
});
|
||||
describe('lexical', function () {
|
||||
it('should test filter syntax', function () {
|
||||
expect(lexical.filterLine.test('abs')).to.equal(true)
|
||||
expect(lexical.filterLine.test('plus:1')).to.equal(true)
|
||||
expect(lexical.filterLine.test('replace: "a", b')).to.equal(true)
|
||||
expect(lexical.filterLine.test('foo: a, "b"')).to.equal(true)
|
||||
expect(lexical.filterLine.test('abs | another')).to.equal(false)
|
||||
expect(lexical.filterLine.test('join: "," | another')).to.equal(false)
|
||||
expect(lexical.filterLine.test('obj_test: k1: "v1", k2: "v2"')).to.equal(true)
|
||||
})
|
||||
|
||||
it('should test number literal', function() {
|
||||
lexical.isLiteral('2.3').should.equal(true);
|
||||
lexical.isLiteral('.3').should.equal(true);
|
||||
lexical.isLiteral('-3.').should.equal(true);
|
||||
lexical.isLiteral('23').should.equal(true);
|
||||
});
|
||||
it('should test boolean literal', function () {
|
||||
expect(lexical.isLiteral('true')).to.equal(true)
|
||||
expect(lexical.isLiteral('TrUE')).to.equal(true)
|
||||
expect(lexical.isLiteral('false')).to.equal(true)
|
||||
})
|
||||
|
||||
it("should test range literal", function() {
|
||||
lexical.isRange("(12..32)").should.equal(true);
|
||||
lexical.isRange("(12..foo)").should.equal(true);
|
||||
lexical.isRange("(foo.bar..foo)").should.equal(true);
|
||||
});
|
||||
it('should test number literal', function () {
|
||||
expect(lexical.isLiteral('2.3')).to.equal(true)
|
||||
expect(lexical.isLiteral('.3')).to.equal(true)
|
||||
expect(lexical.isLiteral('-3.')).to.equal(true)
|
||||
expect(lexical.isLiteral('23')).to.equal(true)
|
||||
})
|
||||
|
||||
it('should test string literal', function() {
|
||||
lexical.isLiteral('""').should.equal(true);
|
||||
lexical.isLiteral('"a\'b"').should.equal(true);
|
||||
lexical.isLiteral("''").should.equal(true);
|
||||
lexical.isLiteral("'a bcd'").should.equal(true);
|
||||
});
|
||||
it('should test range literal', function () {
|
||||
expect(lexical.isRange('(12..32)')).to.equal(true)
|
||||
expect(lexical.isRange('(12..foo)')).to.equal(true)
|
||||
expect(lexical.isRange('(foo.bar..foo)')).to.equal(true)
|
||||
})
|
||||
|
||||
describe('.isVariable()', function() {
|
||||
it('should return true for foo', function() {
|
||||
lexical.isVariable("foo").should.equal(true);
|
||||
});
|
||||
it('should return true for.bar.foo', function() {
|
||||
lexical.isVariable("foo.bar.foo").should.equal(true);
|
||||
});
|
||||
it('should return true for foo[0].b', function() {
|
||||
lexical.isVariable("foo[0].b").should.equal(true);
|
||||
});
|
||||
it('should return true for 0a', function() {
|
||||
lexical.isVariable("0a").should.equal(true);
|
||||
});
|
||||
it('should return true for foo[a.b]', function() {
|
||||
lexical.isVariable("foo[a.b]").should.equal(true);
|
||||
});
|
||||
it('should return true for foo[a.b]', function() {
|
||||
lexical.isVariable("foo['a[0]']").should.equal(true);
|
||||
});
|
||||
it('should return true for "var-1"', function() {
|
||||
lexical.isVariable("var-1").should.equal(true);
|
||||
});
|
||||
it('should return true for "-var"', function() {
|
||||
lexical.isVariable("-var").should.equal(true);
|
||||
});
|
||||
it('should return true for "var-"', function() {
|
||||
lexical.isVariable("var-").should.equal(true);
|
||||
});
|
||||
it('should return true for "3-4"', function() {
|
||||
lexical.isVariable("3-4").should.equal(true);
|
||||
});
|
||||
});
|
||||
it('should test string literal', function () {
|
||||
expect(lexical.isLiteral('""')).to.equal(true)
|
||||
expect(lexical.isLiteral('"a\'b"')).to.equal(true)
|
||||
expect(lexical.isLiteral("''")).to.equal(true)
|
||||
expect(lexical.isLiteral("'a bcd'")).to.equal(true)
|
||||
})
|
||||
|
||||
it('should test none literal', function() {
|
||||
lexical.isLiteral('2a').should.equal(false);
|
||||
lexical.isLiteral('"x').should.equal(false);
|
||||
lexical.isLiteral('a2').should.equal(false);
|
||||
});
|
||||
describe('.isVariable()', function () {
|
||||
it('should return true for foo', function () {
|
||||
expect(lexical.isVariable('foo')).to.equal(true)
|
||||
})
|
||||
it('should return true for.bar.foo', function () {
|
||||
expect(lexical.isVariable('foo.bar.foo')).to.equal(true)
|
||||
})
|
||||
it('should return true for foo[0].b', function () {
|
||||
expect(lexical.isVariable('foo[0].b')).to.equal(true)
|
||||
})
|
||||
it('should return true for 0a', function () {
|
||||
expect(lexical.isVariable('0a')).to.equal(true)
|
||||
})
|
||||
it('should return true for foo[a.b]', function () {
|
||||
expect(lexical.isVariable('foo[a.b]')).to.equal(true)
|
||||
})
|
||||
it('should return true for foo[a.b]', function () {
|
||||
expect(lexical.isVariable("foo['a[0]']")).to.equal(true)
|
||||
})
|
||||
it('should return true for "var-1"', function () {
|
||||
expect(lexical.isVariable('var-1')).to.equal(true)
|
||||
})
|
||||
it('should return true for "-var"', function () {
|
||||
expect(lexical.isVariable('-var')).to.equal(true)
|
||||
})
|
||||
it('should return true for "var-"', function () {
|
||||
expect(lexical.isVariable('var-')).to.equal(true)
|
||||
})
|
||||
it('should return true for "3-4"', function () {
|
||||
expect(lexical.isVariable('3-4')).to.equal(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('should test none variable', function() {
|
||||
lexical.isVariable("a.").should.equal(false);
|
||||
lexical.isVariable(".b").should.equal(false);
|
||||
lexical.isVariable(".").should.equal(false);
|
||||
lexical.isVariable("[0][12].bar[0]").should.equal(false);
|
||||
});
|
||||
it('should test none literal', function () {
|
||||
expect(lexical.isLiteral('2a')).to.equal(false)
|
||||
expect(lexical.isLiteral('"x')).to.equal(false)
|
||||
expect(lexical.isLiteral('a2')).to.equal(false)
|
||||
})
|
||||
|
||||
it('should parse boolean literal', function() {
|
||||
lexical.parseLiteral('true').should.equal(true);
|
||||
lexical.parseLiteral('TrUE').should.equal(true);
|
||||
lexical.parseLiteral('false').should.equal(false);
|
||||
});
|
||||
it('should test none variable', function () {
|
||||
expect(lexical.isVariable('a.')).to.equal(false)
|
||||
expect(lexical.isVariable('.b')).to.equal(false)
|
||||
expect(lexical.isVariable('.')).to.equal(false)
|
||||
expect(lexical.isVariable('[0][12].bar[0]')).to.equal(false)
|
||||
})
|
||||
|
||||
it('should parse number literal', function() {
|
||||
lexical.parseLiteral('2.3').should.equal(2.3);
|
||||
lexical.parseLiteral('.32').should.equal(0.32);
|
||||
lexical.parseLiteral('-23.').should.equal(-23);
|
||||
lexical.parseLiteral('23').should.equal(23);
|
||||
});
|
||||
describe('.parseLiteral()', function () {
|
||||
it('should parse boolean literal', function () {
|
||||
expect(lexical.parseLiteral('true')).to.equal(true)
|
||||
expect(lexical.parseLiteral('TrUE')).to.equal(true)
|
||||
expect(lexical.parseLiteral('false')).to.equal(false)
|
||||
})
|
||||
|
||||
it('should parse string literal', function() {
|
||||
lexical.parseLiteral('"ab\'c"').should.equal("ab\'c");
|
||||
});
|
||||
it('should parse number literal', function () {
|
||||
expect(lexical.parseLiteral('2.3')).to.equal(2.3)
|
||||
expect(lexical.parseLiteral('.32')).to.equal(0.32)
|
||||
expect(lexical.parseLiteral('-23.')).to.equal(-23)
|
||||
expect(lexical.parseLiteral('23')).to.equal(23)
|
||||
})
|
||||
|
||||
describe('.matchValue()', function(){
|
||||
it('should match -5-5', function() {
|
||||
var match = lexical.matchValue('-5-5');
|
||||
expect(match && match[0]).to.equal('-5-5');
|
||||
});
|
||||
it('should match 4-3', function() {
|
||||
var match = lexical.matchValue('4-3');
|
||||
expect(match && match[0]).to.equal('4-3');
|
||||
});
|
||||
it('should match 4-3', function() {
|
||||
var match = lexical.matchValue('4-3');
|
||||
expect(match && match[0]).to.equal('4-3');
|
||||
});
|
||||
it('should match var-1', function() {
|
||||
var match = lexical.matchValue('var-1');
|
||||
expect(match && match[0]).to.equal('var-1');
|
||||
});
|
||||
});
|
||||
});
|
||||
it('should parse string literal', function () {
|
||||
expect(lexical.parseLiteral('"ab\'c"')).to.equal("ab'c")
|
||||
})
|
||||
|
||||
it('should throw if non-literal', function () {
|
||||
var fn = () => lexical.parseLiteral('a')
|
||||
expect(fn).to.throw("cannot parse 'a' as literal")
|
||||
})
|
||||
})
|
||||
|
||||
describe('.matchValue()', function () {
|
||||
it('should match -5-5', function () {
|
||||
var match = lexical.matchValue('-5-5')
|
||||
expect(match && match[0]).to.equal('-5-5')
|
||||
})
|
||||
it('should match 4-3', function () {
|
||||
var match = lexical.matchValue('4-3')
|
||||
expect(match && match[0]).to.equal('4-3')
|
||||
})
|
||||
it('should match 4-3', function () {
|
||||
var match = lexical.matchValue('4-3')
|
||||
expect(match && match[0]).to.equal('4-3')
|
||||
})
|
||||
it('should match var-1', function () {
|
||||
var match = lexical.matchValue('var-1')
|
||||
expect(match && match[0]).to.equal('var-1')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+136
-175
@@ -1,177 +1,138 @@
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
const Liquid = require('..');
|
||||
const mock = require('mock-fs');
|
||||
chai.use(require("chai-as-promised"));
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
const Liquid = require('..')
|
||||
const mock = require('mock-fs')
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('liquid', function() {
|
||||
var engine, strictEngine, ctx;
|
||||
beforeEach(function() {
|
||||
ctx = {
|
||||
name: 'harttle',
|
||||
arr: [-2, 'a'],
|
||||
obj: {
|
||||
foo: 'bar'
|
||||
}
|
||||
};
|
||||
engine = Liquid({
|
||||
root: '/root/',
|
||||
extname: '.html'
|
||||
});
|
||||
strictEngine = Liquid({
|
||||
root: '/root',
|
||||
extname: '.html',
|
||||
strict_filters: true
|
||||
});
|
||||
mock({
|
||||
'/root/files/foo.html': 'foo',
|
||||
'/root/files/name.html': 'My name is {{name}}.',
|
||||
'/un-readable.html': mock.file({
|
||||
mode: '0000'
|
||||
})
|
||||
});
|
||||
});
|
||||
afterEach(function() {
|
||||
mock.restore();
|
||||
});
|
||||
describe('{{output}}', function() {
|
||||
it('should output object', function() {
|
||||
return engine.parseAndRender('{{obj}}', ctx).should.eventually.equal('{"foo":"bar"}');
|
||||
});
|
||||
it('should output array', function() {
|
||||
return engine.parseAndRender('{{arr}}', ctx).should.eventually.equal('[-2,"a"]');
|
||||
});
|
||||
it('should output undefined to empty', function() {
|
||||
return engine.parseAndRender('foo{{zzz}}bar', ctx).should.eventually.equal('foobar');
|
||||
});
|
||||
it('should render as null when filter undefined', function() {
|
||||
return engine.parseAndRender('{{"foo" | filter1}}', ctx).should.eventually.equal('foo');
|
||||
});
|
||||
it('should throw upon undefined filter when strict_filters set', function() {
|
||||
return expect(strictEngine.parseAndRender('{{arr | filter1}}', ctx)).to
|
||||
.be.rejectedWith(/undefined filter: filter1/);
|
||||
});
|
||||
});
|
||||
it('should parse html', function() {
|
||||
(function() {
|
||||
engine.parse('{{obj}}');
|
||||
}).should.not.throw();
|
||||
(function() {
|
||||
engine.parse('<html><head>{{obj}}</head></html>');
|
||||
}).should.not.throw();
|
||||
});
|
||||
it('should render template multiple times', function() {
|
||||
var template = engine.parse('{{obj}}');
|
||||
return engine.render(template, ctx)
|
||||
.then((result) => {
|
||||
expect(result).to.equal('{"foo":"bar"}');
|
||||
return engine.render(template, ctx);
|
||||
})
|
||||
.then((result) => {
|
||||
return expect(result).to.equal('{"foo":"bar"}');
|
||||
});
|
||||
});
|
||||
it('should render filters', function() {
|
||||
var template = engine.parse('<p>{{arr | join: "_"}}</p>');
|
||||
return engine.render(template, ctx).should.eventually.equal('<p>-2_a</p>');
|
||||
});
|
||||
it('should render accessive filters', function() {
|
||||
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
|
||||
'{{ my_array | first }}';
|
||||
return expect(engine.parseAndRender(src)).to.eventually.equal('apples');
|
||||
});
|
||||
describe('#renderFile()', function() {
|
||||
it('should render file', function() {
|
||||
return expect(engine.renderFile('/root/files/foo.html', ctx))
|
||||
.to.eventually.equal('foo');
|
||||
});
|
||||
it('should accept relative path', function() {
|
||||
return expect(engine.renderFile('files/foo.html'))
|
||||
.to.eventually.equal('foo');
|
||||
});
|
||||
it('should resolve array as root', function(){
|
||||
engine = Liquid({
|
||||
root: ['/boo', '/root/'],
|
||||
extname: '.html'
|
||||
});
|
||||
return expect(engine.renderFile('files/foo.html'))
|
||||
.to.eventually.equal('foo');
|
||||
});
|
||||
it('should default root to cwd', function(){
|
||||
var files = {};
|
||||
files[process.cwd() + '/foo.html'] = 'FOO';
|
||||
mock(files);
|
||||
describe('liquid', function () {
|
||||
var engine, strictEngine, ctx
|
||||
beforeEach(function () {
|
||||
ctx = {
|
||||
name: 'harttle',
|
||||
arr: [-2, 'a'],
|
||||
obj: {
|
||||
foo: 'bar'
|
||||
}
|
||||
}
|
||||
engine = Liquid({
|
||||
root: '/root/',
|
||||
extname: '.html'
|
||||
})
|
||||
strictEngine = Liquid({
|
||||
root: '/root',
|
||||
extname: '.html',
|
||||
strict_filters: true
|
||||
})
|
||||
mock({
|
||||
'/root/files/bar': 'bar',
|
||||
'/root/files/foo.html': 'foo',
|
||||
'/root/files/name.html': 'My name is {{name}}.',
|
||||
'/un-readable.html': mock.file({
|
||||
mode: '0000'
|
||||
})
|
||||
})
|
||||
})
|
||||
afterEach(function () {
|
||||
mock.restore()
|
||||
})
|
||||
describe('Liquid', function () {
|
||||
it('should ignore invalid root option', function () {
|
||||
var liquid = Liquid({ root: /regex/ })
|
||||
expect(liquid.options.root).to.deep.equal([])
|
||||
})
|
||||
})
|
||||
describe('{{value}}', function () {
|
||||
it('should value object', function () {
|
||||
return expect(engine.parseAndRender('{{obj}}', ctx)).to.eventually.equal('{"foo":"bar"}')
|
||||
})
|
||||
it('should value array', function () {
|
||||
return expect(engine.parseAndRender('{{arr}}', ctx)).to.eventually.equal('[-2,"a"]')
|
||||
})
|
||||
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 () {
|
||||
return expect(engine.parseAndRender('{{"foo" | filter1}}', ctx)).to.eventually.equal('foo')
|
||||
})
|
||||
it('should throw upon undefined filter when strict_filters set', function () {
|
||||
return expect(strictEngine.parseAndRender('{{arr | filter1}}', ctx)).to
|
||||
.be.rejectedWith(/undefined filter: filter1/)
|
||||
})
|
||||
})
|
||||
it('should parse html', function () {
|
||||
expect(function () {
|
||||
engine.parse('{{obj}}')
|
||||
}).to.not.throw()
|
||||
expect(function () {
|
||||
engine.parse('<html><head>{{obj}}</head></html>')
|
||||
}).to.not.throw()
|
||||
})
|
||||
it('should render template multiple times', function () {
|
||||
var template = engine.parse('{{obj}}')
|
||||
return engine.render(template, ctx)
|
||||
.then(result => expect(result).to.equal('{"foo":"bar"}'))
|
||||
.then(() => engine.render(template, ctx))
|
||||
.then((result) => expect(result).to.equal('{"foo":"bar"}'))
|
||||
})
|
||||
it('should render filters', function () {
|
||||
var template = engine.parse('<p>{{arr | join: "_"}}</p>')
|
||||
return expect(engine.render(template, ctx)).to.eventually.equal('<p>-2_a</p>')
|
||||
})
|
||||
it('should render accessive filters', function () {
|
||||
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
|
||||
'{{ my_array | first }}'
|
||||
return expect(engine.parseAndRender(src)).to.eventually.equal('apples')
|
||||
})
|
||||
describe('#renderFile()', function () {
|
||||
it('should render file', function () {
|
||||
return expect(engine.renderFile('/root/files/foo.html', ctx))
|
||||
.to.eventually.equal('foo')
|
||||
})
|
||||
it('should find files without extname', function () {
|
||||
var engine = Liquid({root: '/root'})
|
||||
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')
|
||||
})
|
||||
it('should resolve array as root', function () {
|
||||
engine = Liquid({
|
||||
root: ['/boo', '/root/'],
|
||||
extname: '.html'
|
||||
})
|
||||
return expect(engine.renderFile('files/foo.html'))
|
||||
.to.eventually.equal('foo')
|
||||
})
|
||||
it('should default root to cwd', function () {
|
||||
var files = {}
|
||||
files[process.cwd() + '/foo.html'] = 'FOO'
|
||||
mock(files)
|
||||
|
||||
engine = Liquid({
|
||||
extname: '.html'
|
||||
});
|
||||
return expect(engine.renderFile('foo.html'))
|
||||
.to.eventually.equal('FOO');
|
||||
});
|
||||
it('should render file with context', function() {
|
||||
return engine.renderFile('/root/files/name.html', ctx).should.eventually.equal('My name is harttle.');
|
||||
});
|
||||
it('should use default extname', function() {
|
||||
return engine.renderFile('files/name', ctx).should.eventually.equal('My name is harttle.');
|
||||
});
|
||||
it('should throw with lookup list when file not exist', function() {
|
||||
engine = Liquid({
|
||||
root: ['/boo', '/root/'],
|
||||
extname: '.html'
|
||||
});
|
||||
return expect(engine.renderFile('/not/exist.html')).to
|
||||
.be.rejectedWith(/failed to lookup \/not\/exist.html in: \/boo,\/root\//i);
|
||||
});
|
||||
it('should throw when file not readable', function() {
|
||||
return expect(engine.renderFile('/un-readable.html')).to
|
||||
.be.rejectedWith(/EACCES/);
|
||||
});
|
||||
});
|
||||
describe('strict', function() {
|
||||
it('should not throw when strict_variables false (default)', function() {
|
||||
return expect(engine.parseAndRender('before{{notdefined}}after', ctx)).to
|
||||
.eventually.equal('beforeafter');
|
||||
});
|
||||
it('should throw when strict_variables true', function() {
|
||||
var tpl = engine.parse('before{{notdefined}}after');
|
||||
var opts = {
|
||||
strict_variables: true
|
||||
};
|
||||
return expect(engine.render(tpl, ctx, opts)).to
|
||||
.be.rejectedWith(/undefined variable: notdefined/);
|
||||
});
|
||||
it('should pass strict_variables to render by parseAndRender', function() {
|
||||
var html = 'before{{notdefined}}after';
|
||||
var opts = {
|
||||
strict_variables: true
|
||||
};
|
||||
return expect(engine.parseAndRender(html, ctx, opts)).to
|
||||
.be.rejectedWith(/undefined variable: notdefined/);
|
||||
});
|
||||
});
|
||||
describe('cache', function() {
|
||||
it('should be disabled by default', function() {
|
||||
return engine.renderFile('files/foo')
|
||||
.then(x => expect(x).to.equal('foo'))
|
||||
.then(() => mock({
|
||||
'/root/files/foo.html': 'bar'
|
||||
}))
|
||||
.then(() => engine.renderFile('files/foo'))
|
||||
.then(x => expect(x).to.equal('bar'));
|
||||
});
|
||||
it('should respect cache=true option', function() {
|
||||
engine = Liquid({
|
||||
root: '/root/',
|
||||
extname: '.html',
|
||||
cache: true
|
||||
});
|
||||
return engine.renderFile('files/foo')
|
||||
.then(x => expect(x).to.equal('foo'))
|
||||
.then(() => mock({
|
||||
'/root/files/foo.html': 'bar'
|
||||
}))
|
||||
.then(() => engine.renderFile('files/foo'))
|
||||
.then(x => expect(x).to.equal('foo'));
|
||||
});
|
||||
});
|
||||
});
|
||||
engine = Liquid({
|
||||
extname: '.html'
|
||||
})
|
||||
return expect(engine.renderFile('foo.html'))
|
||||
.to.eventually.equal('FOO')
|
||||
})
|
||||
it('should render file with context', function () {
|
||||
return expect(engine.renderFile('/root/files/name.html', ctx)).to.eventually.equal('My name is harttle.')
|
||||
})
|
||||
it('should use default extname', function () {
|
||||
return expect(engine.renderFile('files/name', ctx)).to.eventually.equal('My name is harttle.')
|
||||
})
|
||||
it('should throw with lookup list when file not exist', function () {
|
||||
engine = Liquid({
|
||||
root: ['/boo', '/root/'],
|
||||
extname: '.html'
|
||||
})
|
||||
return expect(engine.renderFile('/not/exist.html')).to
|
||||
.be.rejectedWith(/failed to lookup \/not\/exist.html in: \/boo,\/root\//i)
|
||||
})
|
||||
it('should throw when file not readable', function () {
|
||||
return expect(engine.renderFile('/un-readable.html')).to
|
||||
.be.rejectedWith(/EACCES/)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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'))
|
||||
})
|
||||
})
|
||||
@@ -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/)
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
})
|
||||
+38
-40
@@ -1,49 +1,47 @@
|
||||
const chai = require("chai");
|
||||
const sinon = require("sinon");
|
||||
const sinonChai = require("sinon-chai");
|
||||
const should = chai.should();
|
||||
const expect = chai.expect;
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
|
||||
chai.use(sinonChai);
|
||||
chai.use(require('sinon-chai'))
|
||||
|
||||
var filter = require('../src/filter.js')();
|
||||
var tag = require('../src/tag.js')();
|
||||
var Template = require('../src/parser.js');
|
||||
var filter = require('../src/filter.js')()
|
||||
var tag = require('../src/tag.js')()
|
||||
var Template = require('../src/parser.js')
|
||||
|
||||
describe('template', function() {
|
||||
var scope, template, add = (l, r) => l + r;
|
||||
describe('template', function () {
|
||||
var template
|
||||
var add = (l, r) => l + r
|
||||
|
||||
beforeEach(function() {
|
||||
filter.clear();
|
||||
filter.register('add', add);
|
||||
beforeEach(function () {
|
||||
filter.clear()
|
||||
filter.register('add', add)
|
||||
|
||||
tag.clear();
|
||||
template = Template(tag, filter);
|
||||
});
|
||||
tag.clear()
|
||||
template = Template(tag, filter)
|
||||
})
|
||||
|
||||
it('should throw when output string illegal', function() {
|
||||
expect(function() {
|
||||
template.parseOutput('/');
|
||||
}).to.throw(/illegal output string/);
|
||||
});
|
||||
it('should throw when value string illegal', function () {
|
||||
expect(function () {
|
||||
template.parseValue('/')
|
||||
}).to.throw(/illegal value string/)
|
||||
})
|
||||
|
||||
it('should parse output string', function() {
|
||||
var tpl = template.parseOutput('foo');
|
||||
expect(tpl.type).to.equal('output');
|
||||
expect(tpl.initial).to.equal('foo');
|
||||
expect(tpl.filters).to.deep.equal([]);
|
||||
});
|
||||
it('should parse 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"');
|
||||
expect(tpl.initial).to.equal('foo');
|
||||
expect(tpl.filters.length).to.equal(1);
|
||||
expect(tpl.filters[0].filter).to.equal(add);
|
||||
});
|
||||
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');
|
||||
expect(tpl.initial).to.equal('foo');
|
||||
expect(tpl.filters.length).to.equal(2);
|
||||
});
|
||||
});
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
+58
-59
@@ -1,67 +1,66 @@
|
||||
const chai = require("chai");
|
||||
const chaiAsPromised = require("chai-as-promised");
|
||||
const should = chai.should();
|
||||
const expect = chai.expect;
|
||||
const sinonChai = require("sinon-chai");
|
||||
const sinon = require("sinon");
|
||||
const chai = require('chai')
|
||||
const chaiAsPromised = require('chai-as-promised')
|
||||
const expect = chai.expect
|
||||
const sinonChai = require('sinon-chai')
|
||||
const sinon = require('sinon')
|
||||
|
||||
chai.use(sinonChai);
|
||||
chai.use(chaiAsPromised);
|
||||
chai.use(sinonChai)
|
||||
chai.use(chaiAsPromised)
|
||||
|
||||
var tag = require('../src/tag.js')();
|
||||
var Scope = require('../src/scope.js');
|
||||
var filter = require('../src/filter')();
|
||||
var Render = require('../src/render.js');
|
||||
var Template = require('../src/parser.js')(tag, filter);
|
||||
var tag = require('../src/tag.js')()
|
||||
var Scope = require('../src/scope.js')
|
||||
var filter = require('../src/filter')()
|
||||
var Render = require('../src/render.js')
|
||||
var Template = require('../src/parser.js')(tag, filter)
|
||||
|
||||
describe('render', function() {
|
||||
var scope, render;
|
||||
describe('render', function () {
|
||||
var scope, render
|
||||
|
||||
beforeEach(function() {
|
||||
scope = Scope.factory({
|
||||
foo: {
|
||||
bar: ['a', 2]
|
||||
}
|
||||
});
|
||||
filter.clear();
|
||||
tag.clear();
|
||||
render = Render();
|
||||
});
|
||||
beforeEach(function () {
|
||||
scope = Scope.factory({
|
||||
foo: {
|
||||
bar: ['a', 2]
|
||||
}
|
||||
})
|
||||
filter.clear()
|
||||
tag.clear()
|
||||
render = Render()
|
||||
})
|
||||
|
||||
describe('.renderTemplates()', function(){
|
||||
it('should throw when scope undefined', function() {
|
||||
expect(function(){
|
||||
render.renderTemplates([]);
|
||||
}).to.throw(/scope undefined/);
|
||||
});
|
||||
describe('.renderTemplates()', function () {
|
||||
it('should throw when scope undefined', function () {
|
||||
expect(function () {
|
||||
render.renderTemplates([])
|
||||
}).to.throw(/scope undefined/)
|
||||
})
|
||||
|
||||
it('should render html', function() {
|
||||
return render.renderTemplates([{type: 'html', value: '<p>'}], scope).should.eventually.equal('<p>');
|
||||
});
|
||||
});
|
||||
it('should render html', function () {
|
||||
return expect(render.renderTemplates([{type: 'html', value: '<p>'}], scope)).to.eventually.equal('<p>')
|
||||
})
|
||||
})
|
||||
|
||||
it('should eval filter with correct arguments', function() {
|
||||
var date = sinon.stub().returns('y');
|
||||
var time = sinon.spy();
|
||||
filter.register('date', date);
|
||||
filter.register('time', time);
|
||||
var tpl = Template.parseOutput('foo.bar[0] | date: "b" | time:2');
|
||||
render.evalOutput(tpl, scope);
|
||||
expect(date).to.have.been.calledWith('a', 'b');
|
||||
expect(time).to.have.been.calledWith('y', 2);
|
||||
});
|
||||
it('should eval filter with correct arguments', function () {
|
||||
var date = sinon.stub().returns('y')
|
||||
var time = sinon.spy()
|
||||
filter.register('date', date)
|
||||
filter.register('time', time)
|
||||
var tpl = Template.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(){
|
||||
it('should throw when scope undefined', function() {
|
||||
expect(function(){
|
||||
render.evalOutput();
|
||||
}).to.throw(/scope undefined/);
|
||||
});
|
||||
it('should eval output', function() {
|
||||
filter.register('date', (l, r) => l + r);
|
||||
filter.register('time', (l, r) => l + 3 * r);
|
||||
var tpl = Template.parseOutput('foo.bar[0] | date: "b" | time:2');
|
||||
expect(render.evalOutput(tpl, scope)).to.equal('ab6');
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('.evalValue()', function () {
|
||||
it('should throw when scope undefined', function () {
|
||||
expect(function () {
|
||||
render.evalValue()
|
||||
}).to.throw(/scope undefined/)
|
||||
})
|
||||
it('should eval value', function () {
|
||||
filter.register('date', (l, r) => l + r)
|
||||
filter.register('time', (l, r) => l + 3 * r)
|
||||
var tpl = Template.parseValue('foo.bar[0] | date: "b" | time:2')
|
||||
expect(render.evalValue(tpl, scope)).to.equal('ab6')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+222
-172
@@ -1,189 +1,239 @@
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
|
||||
var Scope = require('../src/scope.js');
|
||||
var Scope = require('../src/scope.js')
|
||||
|
||||
describe('scope', function() {
|
||||
var scope, ctx;
|
||||
beforeEach(function() {
|
||||
ctx = {
|
||||
foo: 'zoo',
|
||||
bar: {
|
||||
zoo: 'coo',
|
||||
"Mr.Smith": 'John',
|
||||
arr: ['a', 'b']
|
||||
}
|
||||
};
|
||||
scope = Scope.factory(ctx);
|
||||
});
|
||||
describe('scope', function () {
|
||||
var scope, ctx
|
||||
beforeEach(function () {
|
||||
ctx = {
|
||||
foo: 'zoo',
|
||||
bar: {
|
||||
zoo: 'coo',
|
||||
'Mr.Smith': 'John',
|
||||
arr: ['a', 'b']
|
||||
}
|
||||
}
|
||||
scope = Scope.factory(ctx)
|
||||
})
|
||||
|
||||
describe('#propertyAccessSeq()', function() {
|
||||
it('should handle dot syntax', function() {
|
||||
expect(scope.propertyAccessSeq('foo.bar'))
|
||||
.to.deep.equal(['foo', 'bar']);
|
||||
});
|
||||
it('should handle [<String>] syntax', function() {
|
||||
expect(scope.propertyAccessSeq('foo["bar"]'))
|
||||
.to.deep.equal(['foo', 'bar']);
|
||||
});
|
||||
it('should handle [<Identifier>] syntax', function() {
|
||||
expect(scope.propertyAccessSeq('foo[foo]'))
|
||||
.to.deep.equal(['foo', 'zoo']);
|
||||
});
|
||||
it('should handle nested access', function() {
|
||||
expect(scope.propertyAccessSeq('foo[bar.zoo]'))
|
||||
.to.deep.equal(['foo', 'coo']);
|
||||
expect(scope.propertyAccessSeq('foo[bar["zoo"]]'))
|
||||
.to.deep.equal(['foo', 'coo']);
|
||||
});
|
||||
});
|
||||
describe('#propertyAccessSeq()', function () {
|
||||
it('should handle dot syntax', function () {
|
||||
expect(scope.propertyAccessSeq('foo.bar'))
|
||||
.to.deep.equal(['foo', 'bar'])
|
||||
})
|
||||
it('should handle [<String>] syntax', function () {
|
||||
expect(scope.propertyAccessSeq('foo["bar"]'))
|
||||
.to.deep.equal(['foo', 'bar'])
|
||||
})
|
||||
it('should handle [<Identifier>] syntax', function () {
|
||||
expect(scope.propertyAccessSeq('foo[foo]'))
|
||||
.to.deep.equal(['foo', 'zoo'])
|
||||
})
|
||||
it('should handle nested access 1', function () {
|
||||
expect(scope.propertyAccessSeq('foo[bar.zoo]'))
|
||||
.to.deep.equal(['foo', 'coo'])
|
||||
})
|
||||
it('should handle nested access 2', function () {
|
||||
expect(scope.propertyAccessSeq('foo[bar["zoo"]]'))
|
||||
.to.deep.equal(['foo', 'coo'])
|
||||
})
|
||||
it('should handle nested access 3', function () {
|
||||
expect(scope.propertyAccessSeq('bar["foo"].zoo'))
|
||||
.to.deep.equal(['bar', 'foo', 'zoo'])
|
||||
})
|
||||
it('should handle nested access 4', function () {
|
||||
expect(scope.propertyAccessSeq('foo[0].bar'))
|
||||
.to.deep.equal(['foo', '0', 'bar'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('#get()', function() {
|
||||
it('should get direct property', function() {
|
||||
expect(scope.get('foo')).equal('zoo');
|
||||
});
|
||||
describe('#get()', function () {
|
||||
it('should get direct property', function () {
|
||||
expect(scope.get('foo')).equal('zoo')
|
||||
})
|
||||
|
||||
it('should get undefined property', function() {
|
||||
function fn() {
|
||||
scope.get('notdefined');
|
||||
}
|
||||
expect(fn).to.not.throw();
|
||||
expect(scope.get('notdefined')).to.equal(undefined);
|
||||
expect(scope.get('')).to.equal(undefined);
|
||||
expect(scope.get(false)).to.equal(undefined);
|
||||
});
|
||||
it('should get undefined property', function () {
|
||||
function fn () {
|
||||
scope.get('notdefined')
|
||||
}
|
||||
expect(fn).to.not.throw()
|
||||
expect(scope.get('notdefined')).to.equal(undefined)
|
||||
expect(scope.get('')).to.equal(undefined)
|
||||
expect(scope.get(false)).to.equal(undefined)
|
||||
})
|
||||
|
||||
it('should throw when [] unbalanced', function() {
|
||||
expect(function() {
|
||||
scope.get('foo[bar');
|
||||
}).to.throw(/unbalanced \[\]/);
|
||||
});
|
||||
it('should throw when [] unbalanced', function () {
|
||||
expect(function () {
|
||||
scope.get('foo[bar')
|
||||
}).to.throw(/unbalanced \[\]/)
|
||||
})
|
||||
|
||||
it('should throw when "" unbalanced', function() {
|
||||
expect(function() {
|
||||
scope.get('foo["bar]');
|
||||
}).to.throw(/unbalanced "/);
|
||||
});
|
||||
it('should throw when "" unbalanced', function () {
|
||||
expect(function () {
|
||||
scope.get('foo["bar]')
|
||||
}).to.throw(/unbalanced "/)
|
||||
})
|
||||
|
||||
it("should throw when '' unbalanced", function() {
|
||||
expect(function() {
|
||||
scope.get("foo['bar]");
|
||||
}).to.throw(/unbalanced '/);
|
||||
});
|
||||
it("should throw when '' unbalanced", function () {
|
||||
expect(function () {
|
||||
scope.get("foo['bar]")
|
||||
}).to.throw(/unbalanced '/)
|
||||
})
|
||||
|
||||
it('should access child property via dot syntax', function() {
|
||||
expect(scope.get('bar.zoo')).to.equal('coo');
|
||||
expect(scope.get('bar.arr')).to.deep.equal(['a', 'b']);
|
||||
});
|
||||
it('should access child property via dot syntax', function () {
|
||||
expect(scope.get('bar.zoo')).to.equal('coo')
|
||||
expect(scope.get('bar.arr')).to.deep.equal(['a', 'b'])
|
||||
})
|
||||
|
||||
it('should access child property via [<String>] syntax', function() {
|
||||
expect(scope.get('bar["zoo"]')).to.equal('coo');
|
||||
});
|
||||
it('should access child property via [<String>] syntax', function () {
|
||||
expect(scope.get('bar["zoo"]')).to.equal('coo')
|
||||
})
|
||||
|
||||
it('should access child property via [<Number>] syntax', function() {
|
||||
expect(scope.get('bar.arr[0]')).to.equal('a');
|
||||
});
|
||||
it('should access child property via [<Number>] syntax', function () {
|
||||
expect(scope.get('bar.arr[0]')).to.equal('a')
|
||||
})
|
||||
|
||||
it('should access child property via [<Identifier>] syntax', function() {
|
||||
expect(scope.get('bar[foo]')).to.equal('coo');
|
||||
});
|
||||
it('should access child property via [<Identifier>] syntax', function () {
|
||||
expect(scope.get('bar[foo]')).to.equal('coo')
|
||||
})
|
||||
|
||||
it('should support nested case', function() {
|
||||
scope.set('posts', {
|
||||
"first": {
|
||||
"name": "A Nice Day"
|
||||
}
|
||||
});
|
||||
scope.set('category', {
|
||||
"diary": ["first"]
|
||||
});
|
||||
expect(scope.get('posts[category.diary[0]].name'), 'A Nice Day');
|
||||
});
|
||||
});
|
||||
it('should return undefined when not exist', function () {
|
||||
expect(scope.get('foo.foo.foo')).to.be.undefined
|
||||
})
|
||||
})
|
||||
|
||||
describe('strict_variables', function() {
|
||||
var scope;
|
||||
beforeEach(function(){
|
||||
scope = Scope.factory(ctx, {
|
||||
strict_variables: true
|
||||
});
|
||||
});
|
||||
it('should throw undefined in strict mode', function() {
|
||||
function fn() {
|
||||
scope.get('notdefined');
|
||||
}
|
||||
expect(fn).to.throw(/undefined variable: notdefined/);
|
||||
});
|
||||
it('should find variable in parent scope', function() {
|
||||
scope.set('foo', 'foo');
|
||||
scope.push({
|
||||
'bar': 'bar'
|
||||
});
|
||||
expect(scope.get('foo')).to.equal('foo');
|
||||
});
|
||||
});
|
||||
describe('#set', function () {
|
||||
it('should set nested value', function () {
|
||||
scope.set('posts', {
|
||||
'first': {
|
||||
'name': 'A Nice Day'
|
||||
}
|
||||
})
|
||||
scope.set('category', {
|
||||
'diary': ['first']
|
||||
})
|
||||
expect(scope.get('posts[category.diary[0]].name'), 'A Nice Day')
|
||||
})
|
||||
|
||||
describe('.getAll()', function() {
|
||||
it('should get all properties when arguments empty', function() {
|
||||
expect(scope.getAll()).deep.equal(ctx);
|
||||
});
|
||||
});
|
||||
it('should create in parent scope if needed', function () {
|
||||
scope.push({})
|
||||
scope.set('bar.coo', 'COO')
|
||||
expect(scope.get('bar.coo')).to.equal('COO')
|
||||
})
|
||||
it('should keep other properties of parent', function () {
|
||||
scope.push({obj: {foo: 'FOO'}})
|
||||
scope.set('obj.bar', 'BAR')
|
||||
expect(scope.get('obj.foo')).to.equal('FOO')
|
||||
})
|
||||
it('should abort if property cannot be set', function () {
|
||||
scope.push({obj: {foo: 'FOO'}})
|
||||
scope.set('obj.foo.bar', 'BAR')
|
||||
expect(scope.get('obj.foo')).to.equal('FOO')
|
||||
})
|
||||
it("should set parents' corresponding value", function () {
|
||||
scope.push({})
|
||||
scope.set('foo', 'bar')
|
||||
scope.pop()
|
||||
expect(scope.get('foo')).to.equal('bar')
|
||||
})
|
||||
})
|
||||
describe('strict_variables', function () {
|
||||
var scope
|
||||
beforeEach(function () {
|
||||
scope = Scope.factory(ctx, {
|
||||
strict_variables: true
|
||||
})
|
||||
})
|
||||
it('should throw when variable not defined', function () {
|
||||
function fn () {
|
||||
scope.get('notdefined')
|
||||
}
|
||||
expect(fn).to.throw(/undefined variable: notdefined/)
|
||||
})
|
||||
it('should throw when parent not defined', function () {
|
||||
function fn () {
|
||||
scope.get('foo.bar.not.defined')
|
||||
}
|
||||
expect(fn).to.throw(/undefined variable: bar/)
|
||||
})
|
||||
it('should throw when itself not defined', function () {
|
||||
scope.set('foo', 'bar')
|
||||
function fn () {
|
||||
scope.get('foo.BAR')
|
||||
}
|
||||
expect(fn).to.throw(/undefined variable: BAR/)
|
||||
})
|
||||
it('should find variable in parent scope', function () {
|
||||
scope.set('foo', 'foo')
|
||||
scope.push({
|
||||
'bar': 'bar'
|
||||
})
|
||||
expect(scope.get('foo')).to.equal('foo')
|
||||
})
|
||||
})
|
||||
|
||||
describe('.push()', function() {
|
||||
it('should throw when trying to push non-object', function() {
|
||||
expect(function() {
|
||||
scope.push(false);
|
||||
}).to.throw();
|
||||
});
|
||||
it('should push scope', function() {
|
||||
scope.set('bar', 'bar');
|
||||
scope.push({
|
||||
foo: 'foo'
|
||||
});
|
||||
expect(scope.get('foo')).to.equal('foo');
|
||||
expect(scope.get('bar')).to.equal('bar');
|
||||
});
|
||||
it('should hide deep properties by push', function(){
|
||||
scope.set('bar', {bar: 'bar'});
|
||||
scope.push({bar: {foo: 'foo'}});
|
||||
expect(scope.get('bar.foo')).to.equal('foo');
|
||||
expect(scope.get('bar.bar')).to.equal(undefined);
|
||||
});
|
||||
});
|
||||
describe('.pop()', function() {
|
||||
it('should pop scope', function() {
|
||||
scope.push({
|
||||
foo: 'foo'
|
||||
});
|
||||
scope.pop();
|
||||
expect(scope.get('foo')).to.equal('zoo');
|
||||
});
|
||||
});
|
||||
describe('.getAll()', function () {
|
||||
it('should get all properties when arguments empty', function () {
|
||||
expect(scope.getAll()).deep.equal(ctx)
|
||||
})
|
||||
})
|
||||
|
||||
describe('.unshift()', function() {
|
||||
it('should throw when trying to unshift non-object', function() {
|
||||
expect(function() {
|
||||
scope.unshift(false);
|
||||
}).to.throw();
|
||||
});
|
||||
it('should unshift scope', function() {
|
||||
scope.unshift({
|
||||
foo: 'blue',
|
||||
foo1: 'foo1'
|
||||
});
|
||||
expect(scope.get('foo')).to.equal('zoo');
|
||||
expect(scope.get('foo1')).to.equal('foo1');
|
||||
});
|
||||
});
|
||||
describe('.shift()', function() {
|
||||
it('should shift scope', function() {
|
||||
scope.unshift({
|
||||
foo: 'blue',
|
||||
foo1: 'foo1'
|
||||
});
|
||||
scope.shift();
|
||||
expect(scope.get('foo')).to.equal('zoo');
|
||||
expect(scope.get('foo1')).to.equal(undefined);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('.push()', function () {
|
||||
it('should throw when trying to push non-object', function () {
|
||||
expect(function () {
|
||||
scope.push(false)
|
||||
}).to.throw()
|
||||
})
|
||||
it('should push scope', function () {
|
||||
scope.set('bar', 'bar')
|
||||
scope.push({
|
||||
foo: 'foo'
|
||||
})
|
||||
expect(scope.get('foo')).to.equal('foo')
|
||||
expect(scope.get('bar')).to.equal('bar')
|
||||
})
|
||||
it('should hide deep properties by push', function () {
|
||||
scope.set('bar', {bar: 'bar'})
|
||||
scope.push({bar: {foo: 'foo'}})
|
||||
expect(scope.get('bar.foo')).to.equal('foo')
|
||||
expect(scope.get('bar.bar')).to.equal(undefined)
|
||||
})
|
||||
})
|
||||
describe('.pop()', function () {
|
||||
it('should pop scope', function () {
|
||||
scope.push({
|
||||
foo: 'foo'
|
||||
})
|
||||
scope.pop()
|
||||
expect(scope.get('foo')).to.equal('zoo')
|
||||
})
|
||||
})
|
||||
|
||||
describe('.unshift()', function () {
|
||||
it('should throw when trying to unshift non-object', function () {
|
||||
expect(function () {
|
||||
scope.unshift(false)
|
||||
}).to.throw()
|
||||
})
|
||||
it('should unshift scope', function () {
|
||||
scope.unshift({
|
||||
foo: 'blue',
|
||||
foo1: 'foo1'
|
||||
})
|
||||
expect(scope.get('foo')).to.equal('zoo')
|
||||
expect(scope.get('foo1')).to.equal('foo1')
|
||||
})
|
||||
})
|
||||
describe('.shift()', function () {
|
||||
it('should shift scope', function () {
|
||||
scope.unshift({
|
||||
foo: 'blue',
|
||||
foo1: 'foo1'
|
||||
})
|
||||
scope.shift()
|
||||
expect(scope.get('foo')).to.equal('zoo')
|
||||
expect(scope.get('foo1')).to.equal(undefined)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+86
-54
@@ -1,65 +1,97 @@
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
var syntax = require('../src/syntax.js');
|
||||
var Scope = require('../src/scope.js');
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
var syntax = require('../src/syntax.js')
|
||||
var Scope = require('../src/scope.js')
|
||||
|
||||
var evalExp = syntax.evalExp;
|
||||
var evalValue = syntax.evalValue;
|
||||
var evalExp = syntax.evalExp
|
||||
var evalValue = syntax.evalValue
|
||||
var isTruthy = syntax.isTruthy
|
||||
|
||||
describe('expression', function() {
|
||||
var scope;
|
||||
describe('expression', function () {
|
||||
var scope
|
||||
|
||||
beforeEach(function() {
|
||||
scope = Scope.factory({
|
||||
one: 1,
|
||||
two: 2,
|
||||
x: 'XXX'
|
||||
});
|
||||
});
|
||||
beforeEach(function () {
|
||||
scope = Scope.factory({
|
||||
one: 1,
|
||||
two: 2,
|
||||
empty: '',
|
||||
x: 'XXX',
|
||||
y: undefined,
|
||||
z: null
|
||||
})
|
||||
})
|
||||
|
||||
it('should eval literals', function() {
|
||||
expect(evalValue('2.3')).to.equal(2.3);
|
||||
expect(evalValue('"foo"')).to.equal("foo");
|
||||
});
|
||||
describe('.evalValue()', function () {
|
||||
it('should eval literals', function () {
|
||||
expect(evalValue('2.3')).to.equal(2.3)
|
||||
expect(evalValue('"foo"')).to.equal('foo')
|
||||
})
|
||||
|
||||
it('should throw on illegal expression', function() {
|
||||
expect(function() {
|
||||
evalExp('1 contains "x"', scope);
|
||||
}).to.throw();
|
||||
});
|
||||
it('should eval variables', function () {
|
||||
expect(evalValue('23', scope)).to.equal(23)
|
||||
expect(evalValue('one', scope)).to.equal(1)
|
||||
expect(evalValue('x', scope)).to.equal('XXX')
|
||||
})
|
||||
|
||||
it('should eval variables', function() {
|
||||
expect(evalValue('23', scope)).to.equal(23);
|
||||
expect(evalValue('one', scope)).to.equal(1);
|
||||
expect(evalValue('x', scope)).to.equal('XXX');
|
||||
});
|
||||
it('should throw if not valid', function () {
|
||||
var fn = () => evalValue('===')
|
||||
expect(fn).to.throw("cannot eval '===' as value")
|
||||
})
|
||||
})
|
||||
|
||||
describe('.evalExp()', function() {
|
||||
describe('.isTruthy()', function () {
|
||||
// Spec: https://shopify.github.io/liquid/basics/truthy-and-falsy/
|
||||
expect(isTruthy(true)).to.be.true
|
||||
expect(isTruthy(false)).to.be.false
|
||||
expect(isTruthy(null)).to.be.false
|
||||
expect(isTruthy('foo')).to.be.true
|
||||
expect(isTruthy('')).to.be.true
|
||||
expect(isTruthy(0)).to.be.true
|
||||
expect(isTruthy(1)).to.be.true
|
||||
expect(isTruthy(1.1)).to.be.true
|
||||
expect(isTruthy([1])).to.be.true
|
||||
expect(isTruthy([])).to.be.true
|
||||
})
|
||||
|
||||
it('should throw when scope undefined', function() {
|
||||
expect(function() {
|
||||
evalExp('');
|
||||
}).to.throw(/scope undefined/);
|
||||
});
|
||||
describe('.evalExp()', function () {
|
||||
it('should throw when scope undefined', function () {
|
||||
expect(function () {
|
||||
evalExp('')
|
||||
}).to.throw(/scope undefined/)
|
||||
})
|
||||
|
||||
it('should eval simple expression', function() {
|
||||
expect(evalExp('1<2', scope)).to.equal(true);
|
||||
expect(evalExp('2<=2', scope)).to.equal(true);
|
||||
expect(evalExp('one<=two', scope)).to.equal(true);
|
||||
expect(evalExp('x contains "x"', scope)).to.equal(false);
|
||||
expect(evalExp('x contains "X"', scope)).to.equal(true);
|
||||
expect(evalExp('"<=" == "<="', scope)).to.equal(true);
|
||||
});
|
||||
it('should eval simple expression', function () {
|
||||
expect(evalExp('1<2', scope)).to.equal(true)
|
||||
expect(evalExp('2<=2', scope)).to.equal(true)
|
||||
expect(evalExp('one<=two', scope)).to.equal(true)
|
||||
expect(evalExp('x contains "x"', scope)).to.equal(false)
|
||||
expect(evalExp('x contains "X"', scope)).to.equal(true)
|
||||
expect(evalExp('1 contains "x"', scope)).to.equal(false)
|
||||
expect(evalExp('y contains "x"', scope)).to.equal(false)
|
||||
expect(evalExp('z contains "x"', scope)).to.equal(false)
|
||||
expect(evalExp('(1..5) contains 3', scope)).to.equal(true)
|
||||
expect(evalExp('(1..5) contains 6', scope)).to.equal(false)
|
||||
expect(evalExp('"<=" == "<="', scope)).to.equal(true)
|
||||
})
|
||||
|
||||
it('should eval complex expression', function() {
|
||||
expect(evalExp('1<2 and x contains "x"', scope)).to.equal(false);
|
||||
expect(evalExp('1<2 or x contains "x"', scope)).to.equal(true);
|
||||
expect(evalExp('false or true', scope)).to.equal(true);
|
||||
});
|
||||
describe('complex expression', function () {
|
||||
it('should support value or value', function () {
|
||||
expect(evalExp('false or true', scope)).to.equal(true)
|
||||
})
|
||||
it('should support < and contains', function () {
|
||||
expect(evalExp('1<2 and x contains "x"', scope)).to.equal(false)
|
||||
})
|
||||
it('should support < or contains', function () {
|
||||
expect(evalExp('1<2 or x contains "x"', scope)).to.equal(true)
|
||||
})
|
||||
it('should support value and !=', function () {
|
||||
expect(evalExp('empty and empty != ""', scope)).to.equal(false)
|
||||
})
|
||||
})
|
||||
|
||||
it("should eval range expression", function() {
|
||||
expect(evalExp('(2..4)', scope)).to.deep.equal([2, 3, 4]);
|
||||
expect(evalExp('(two..4)', scope)).to.deep.equal([2, 3, 4]);
|
||||
});
|
||||
});
|
||||
});
|
||||
it('should eval range expression', function () {
|
||||
expect(evalExp('(2..4)', scope)).to.deep.equal([2, 3, 4])
|
||||
expect(evalExp('(two..4)', scope)).to.deep.equal([2, 3, 4])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+92
-67
@@ -1,73 +1,98 @@
|
||||
const chai = require("chai");
|
||||
const sinon = require("sinon");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("sinon-chai"));
|
||||
const chai = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const expect = chai.expect
|
||||
chai.use(require('sinon-chai'))
|
||||
|
||||
var tag = require('../src/tag.js')();
|
||||
var Scope = require('../src/scope.js');
|
||||
var tag = require('../src/tag.js')()
|
||||
var Scope = require('../src/scope.js')
|
||||
|
||||
describe('tag', function() {
|
||||
var scope;
|
||||
before(function() {
|
||||
scope = Scope.factory({
|
||||
foo: 'bar',
|
||||
arr: [2, 1]
|
||||
});
|
||||
tag.clear();
|
||||
});
|
||||
describe('tag', function () {
|
||||
var scope
|
||||
before(function () {
|
||||
scope = Scope.factory({
|
||||
foo: 'bar',
|
||||
arr: [2, 1],
|
||||
bar: {
|
||||
coo: 'uoo'
|
||||
}
|
||||
})
|
||||
tag.clear()
|
||||
})
|
||||
|
||||
it('should throw when not registered', function() {
|
||||
expect(function() {
|
||||
tag.construct({
|
||||
type: 'tag',
|
||||
value: 'foo',
|
||||
name: 'foo'
|
||||
}, []);
|
||||
}).to.throw(/tag foo not found/);
|
||||
});
|
||||
it('should throw when not registered', function () {
|
||||
expect(function () {
|
||||
tag.construct({
|
||||
type: 'tag',
|
||||
value: 'foo',
|
||||
name: 'foo'
|
||||
}, [])
|
||||
}).to.throw(/tag foo not found/)
|
||||
})
|
||||
|
||||
it('should register simple tag', function() {
|
||||
expect(
|
||||
function() {
|
||||
tag.register('foo', {
|
||||
render: x => 'bar'
|
||||
});
|
||||
}).not.throw();
|
||||
});
|
||||
it('should register simple tag', function () {
|
||||
expect(function () {
|
||||
tag.register('foo', {
|
||||
render: x => 'bar'
|
||||
})
|
||||
}).not.throw()
|
||||
})
|
||||
|
||||
it('should call tag.render', function() {
|
||||
var spy = sinon.spy(),
|
||||
tokens = [];
|
||||
tag.register('foo', {
|
||||
render: spy
|
||||
});
|
||||
return tag
|
||||
.construct({
|
||||
type: 'tag',
|
||||
value: 'foo',
|
||||
name: 'foo'
|
||||
}, [])
|
||||
.render(scope, {})
|
||||
.then(() => expect(spy).to.have.been.called);
|
||||
});
|
||||
it('should call tag.render', function () {
|
||||
var spy = sinon.spy()
|
||||
tag.register('foo', {
|
||||
render: spy
|
||||
})
|
||||
return tag
|
||||
.construct({
|
||||
type: 'tag',
|
||||
value: 'foo',
|
||||
name: 'foo'
|
||||
}, [])
|
||||
.render(scope, {})
|
||||
.then(() => expect(spy).to.have.been.called)
|
||||
})
|
||||
|
||||
it('should call tag.render with resolved hash', function() {
|
||||
var spy = sinon.spy(),
|
||||
tokens = [];
|
||||
tag.register('foo', {
|
||||
render: spy
|
||||
});
|
||||
var token = {
|
||||
type: 'tag',
|
||||
value: 'foo aa:foo bb: arr[0] cc: 2.3',
|
||||
name: 'foo',
|
||||
args: 'aa:foo bb: arr[0] cc: 2.3'
|
||||
};
|
||||
return tag.construct(token, []).render(scope, {})
|
||||
.then(() => expect(spy).to.have.been.calledWithMatch(scope, {
|
||||
aa: 'bar',
|
||||
bb: 2,
|
||||
cc: 2.3
|
||||
}));
|
||||
});
|
||||
});
|
||||
describe('hash', function () {
|
||||
var spy, token
|
||||
beforeEach(function () {
|
||||
spy = sinon.spy()
|
||||
tag.register('foo', {
|
||||
render: spy
|
||||
})
|
||||
token = {
|
||||
type: 'tag',
|
||||
value: 'foo aa:foo bb: arr[0] cc: 2.3\ndd:bar.coo',
|
||||
name: 'foo',
|
||||
args: 'aa:foo bb: arr[0] cc: 2.3\ndd:bar.coo'
|
||||
}
|
||||
})
|
||||
it('should call tag.render with scope', function () {
|
||||
return tag.construct(token, []).render(scope, {})
|
||||
.then(() => expect(spy).to.have.been.calledWithMatch(scope))
|
||||
})
|
||||
it('should resolve identifier hash', function () {
|
||||
return tag.construct(token, []).render(scope, {})
|
||||
.then(() => expect(spy).to.have.been.calledWithMatch({}, {
|
||||
aa: 'bar'
|
||||
}))
|
||||
})
|
||||
it('should accept space between key/value', function () {
|
||||
return tag.construct(token, []).render(scope, {})
|
||||
.then(() => expect(spy).to.have.been.calledWithMatch({}, {
|
||||
bb: 2
|
||||
}))
|
||||
})
|
||||
it('should resolve number value hash', function () {
|
||||
return tag.construct(token, []).render(scope, {})
|
||||
.then(() => expect(spy).to.have.been.calledWithMatch(scope, {
|
||||
cc: 2.3
|
||||
}))
|
||||
})
|
||||
it('should resolve property access hash', function () {
|
||||
return tag.construct(token, []).render(scope, {})
|
||||
.then(() => expect(spy).to.have.been.calledWithMatch(scope, {
|
||||
dd: 'uoo'
|
||||
}))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+51
-51
@@ -1,53 +1,53 @@
|
||||
const Liquid = require('../..');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/assign', function() {
|
||||
var liquid = Liquid();
|
||||
it('should throw when variable expression illegal', function() {
|
||||
var src = '{% assign / %}';
|
||||
var ctx = {};
|
||||
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/);
|
||||
});
|
||||
describe('tags/assign', function () {
|
||||
var liquid = Liquid()
|
||||
it('should throw when variable expression illegal', function () {
|
||||
var src = '{% assign / %}'
|
||||
var ctx = {}
|
||||
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/)
|
||||
})
|
||||
|
||||
it('should assign as string', function() {
|
||||
var src = '{% assign foo="bar" %}{{foo}}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('bar');
|
||||
});
|
||||
it('should assign as array', function() {
|
||||
var src = '{% assign foo=(1..3) %}{{foo}}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('[1,2,3]');
|
||||
});
|
||||
it('should assign as filter result', function() {
|
||||
var src = '{% assign foo="a b" | capitalize | split: " " | first %}{{foo}}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('A');
|
||||
});
|
||||
it('should assign var-1', function() {
|
||||
var src = '{% assign var-1 = 5 %}{{ var-1 }}';
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
|
||||
});
|
||||
it('should assign var-', function() {
|
||||
var src = '{% assign var- = 5 %}{{ var- }}';
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
|
||||
});
|
||||
it('should assign -var', function() {
|
||||
var src = '{% assign -var = 5 %}{{ -var }}';
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
|
||||
});
|
||||
it('should assign -5-5', function() {
|
||||
var src = '{% assign -5-5 = 5 %}{{ -5-5 }}';
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
|
||||
});
|
||||
it('should assign 4-3', function() {
|
||||
var src = '{% assign 4-3 = 5 %}{{ 4-3 }}';
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
|
||||
});
|
||||
it('should not assign -6', function() {
|
||||
var src = '{% assign -6 = 5 %}{{ -6 }}';
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('-6');
|
||||
});
|
||||
});
|
||||
it('should assign as string', function () {
|
||||
var src = '{% assign foo="bar" %}{{foo}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('bar')
|
||||
})
|
||||
it('should assign as array', function () {
|
||||
var src = '{% assign foo=(1..3) %}{{foo}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('[1,2,3]')
|
||||
})
|
||||
it('should assign as filter result', function () {
|
||||
var src = '{% assign foo="a b" | capitalize | split: " " | first %}{{foo}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('A')
|
||||
})
|
||||
it('should assign var-1', function () {
|
||||
var src = '{% assign var-1 = 5 %}{{ var-1 }}'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
|
||||
})
|
||||
it('should assign var-', function () {
|
||||
var src = '{% assign var- = 5 %}{{ var- }}'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
|
||||
})
|
||||
it('should assign -var', function () {
|
||||
var src = '{% assign -var = 5 %}{{ -var }}'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
|
||||
})
|
||||
it('should assign -5-5', function () {
|
||||
var src = '{% assign -5-5 = 5 %}{{ -5-5 }}'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
|
||||
})
|
||||
it('should assign 4-3', function () {
|
||||
var src = '{% assign 4-3 = 5 %}{{ 4-3 }}'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
|
||||
})
|
||||
it('should not assign -6', function () {
|
||||
var src = '{% assign -6 = 5 %}{{ -6 }}'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('-6')
|
||||
})
|
||||
})
|
||||
|
||||
+22
-22
@@ -1,26 +1,26 @@
|
||||
const Liquid = require('../..');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/capture', function() {
|
||||
var liquid = Liquid();
|
||||
describe('tags/capture', function () {
|
||||
var liquid = Liquid()
|
||||
|
||||
it('should support capture', function() {
|
||||
var src = '{% capture f %}{{"a" | capitalize}}{%endcapture%}{{f}}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('A');
|
||||
});
|
||||
it('should support capture', function () {
|
||||
var src = '{% capture f %}{{"a" | capitalize}}{%endcapture%}{{f}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('A')
|
||||
})
|
||||
|
||||
it('should throw on invalid identifier', function() {
|
||||
var src = '{% capture = %}{%endcapture%}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/= not valid identifier/);
|
||||
});
|
||||
it('should throw on invalid identifier', function () {
|
||||
var src = '{% capture = %}{%endcapture%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/= not valid identifier/)
|
||||
})
|
||||
|
||||
it('should throw when capture not closed', function() {
|
||||
var src = '{%capture c%}{{c}}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/tag .* not closed/);
|
||||
});
|
||||
});
|
||||
it('should throw when capture not closed', function () {
|
||||
var src = '{%capture c%}{{c}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/tag .* not closed/)
|
||||
})
|
||||
})
|
||||
|
||||
+46
-39
@@ -1,45 +1,52 @@
|
||||
const Liquid = require('../..');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/case', function() {
|
||||
var liquid = Liquid();
|
||||
describe('tags/case', function () {
|
||||
var liquid = Liquid()
|
||||
|
||||
it('should support case 1', function() {
|
||||
var src = '{% case "foo"%}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/{% case "foo"%} not closed/);
|
||||
});
|
||||
it('should support case 2', function() {
|
||||
var src = '{% case "foo"%}' +
|
||||
it('should reject if not closed', function () {
|
||||
var src = '{% case "foo"%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/{% case "foo"%} not closed/)
|
||||
})
|
||||
it('should hit the specified case', function () {
|
||||
var src = '{% case "foo"%}' +
|
||||
'{% when "foo" %}foo{% when "bar"%}bar' +
|
||||
'{%endcase%}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('foo');
|
||||
});
|
||||
it('should support case 3', function() {
|
||||
var src = '{% case empty %}' +
|
||||
'{%endcase%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('foo')
|
||||
})
|
||||
it('should resolve empty string if not hit', function () {
|
||||
var src = '{% case empty %}' +
|
||||
'{% when "foo" %}foo{% when ""%}bar' +
|
||||
'{%endcase%}';
|
||||
var ctx = {
|
||||
empty: ''
|
||||
};
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('bar');
|
||||
});
|
||||
it('should support case 4', function() {
|
||||
var src = '{% case false %}' +
|
||||
'{%endcase%}'
|
||||
var ctx = {
|
||||
empty: ''
|
||||
}
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('bar')
|
||||
})
|
||||
it('should accept empty string as branch name', function () {
|
||||
var src = '{% case false %}' +
|
||||
'{% when "foo" %}foo{% when ""%}bar' +
|
||||
'{%endcase%}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('');
|
||||
});
|
||||
it('should support case 5', function() {
|
||||
var src = '{% case "a" %}' +
|
||||
'{%endcase%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
it('should support boolean case', function () {
|
||||
var src = '{% case false %}' +
|
||||
'{% when "foo" %}foo{% when false%}bar' +
|
||||
'{%endcase%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('bar')
|
||||
})
|
||||
it('should support else branch', function () {
|
||||
var src = '{% case "a" %}' +
|
||||
'{% when "b" %}b{% when "c"%}c{%else %}d' +
|
||||
'{%endcase%}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('d');
|
||||
});
|
||||
});
|
||||
'{%endcase%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('d')
|
||||
})
|
||||
})
|
||||
|
||||
+32
-22
@@ -1,23 +1,33 @@
|
||||
const Liquid = require('../..');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/comment', function() {
|
||||
var liquid = Liquid();
|
||||
it('should support comment 1', function() {
|
||||
var src = '{% comment %}{% raw%}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/{% comment %} not closed/);
|
||||
});
|
||||
it('should support comment 2', function() {
|
||||
var src = 'My name is {% comment %}super{% endcomment %} Shopify.';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('My name is Shopify.');
|
||||
});
|
||||
it('should support comment 3', function() {
|
||||
var src = '{% comment %}\n{{ foo}} \n{% endcomment %}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('');
|
||||
});
|
||||
});
|
||||
describe('tags/comment', function () {
|
||||
var liquid = Liquid()
|
||||
it('should support empty content', function () {
|
||||
var src = '{% comment %}{% raw%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/{% comment %} not closed/)
|
||||
})
|
||||
it('should ignore plain string', function () {
|
||||
var src = 'My name is {% comment %}super{% endcomment %} Shopify.'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('My name is Shopify.')
|
||||
})
|
||||
it('should ignore output tokens', function () {
|
||||
var src = '{% comment %}\n{{ foo}} \n{% endcomment %}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
it('should ignore tag tokens', function () {
|
||||
var src = '{% comment %}{%if true%}true{%else%}false{%endif%}{% endcomment %}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
it('should ignore un-balenced tag tokens', function () {
|
||||
var src = '{% comment %}{%if true%}true{%else%}false{% endcomment %}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
})
|
||||
|
||||
+33
-33
@@ -1,39 +1,39 @@
|
||||
const Liquid = require('../..');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/cycle', function() {
|
||||
var liquid = Liquid();
|
||||
describe('tags/cycle', function () {
|
||||
var liquid = Liquid()
|
||||
|
||||
it('should support cycle', function() {
|
||||
var src = "{% cycle '1', '2', '3' %}";
|
||||
return expect(liquid.parseAndRender(src + src + src + src))
|
||||
.to.eventually.equal('1231');
|
||||
});
|
||||
it('should support cycle', function () {
|
||||
var src = "{% cycle '1', '2', '3' %}"
|
||||
return expect(liquid.parseAndRender(src + src + src + src))
|
||||
.to.eventually.equal('1231')
|
||||
})
|
||||
|
||||
it('should throw when cycle candidates empty', function() {
|
||||
return expect(liquid.parseAndRender('{%cycle%}'))
|
||||
.to.be.rejectedWith(/empty candidates/);
|
||||
});
|
||||
it('should throw when cycle candidates empty', function () {
|
||||
return expect(liquid.parseAndRender('{%cycle%}'))
|
||||
.to.be.rejectedWith(/empty candidates/)
|
||||
})
|
||||
|
||||
it('should support cycle in for block', function() {
|
||||
var src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}';
|
||||
var ctx = {
|
||||
one: 1
|
||||
};
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('1e1e1');
|
||||
});
|
||||
it('should support cycle in for block', function () {
|
||||
var src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}'
|
||||
var ctx = {
|
||||
one: 1
|
||||
}
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('1e1e1')
|
||||
})
|
||||
|
||||
it('should support cycle group', function() {
|
||||
var src = "{% cycle one: '1', '2', '3'%}" +
|
||||
it('should support cycle group', function () {
|
||||
var src = "{% cycle one: '1', '2', '3'%}" +
|
||||
"{% cycle 1: '1', '2', '3'%}" +
|
||||
"{% cycle 2: '1', '2', '3'%}";
|
||||
var ctx = {
|
||||
one: 1
|
||||
};
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('121');
|
||||
});
|
||||
});
|
||||
"{% cycle 2: '1', '2', '3'%}"
|
||||
var ctx = {
|
||||
one: 1
|
||||
}
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('121')
|
||||
})
|
||||
})
|
||||
|
||||
+33
-33
@@ -1,38 +1,38 @@
|
||||
const Liquid = require('../..');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/decrement', function() {
|
||||
var liquid = Liquid();
|
||||
describe('tags/decrement', function () {
|
||||
var liquid = Liquid()
|
||||
|
||||
it('should throw when variable expression illegal', function() {
|
||||
var src = '{% decrement / %}{{one}}';
|
||||
var ctx = {};
|
||||
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/);
|
||||
});
|
||||
it('should throw when variable expression illegal', function () {
|
||||
var src = '{% decrement / %}{{one}}'
|
||||
var ctx = {}
|
||||
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/)
|
||||
})
|
||||
|
||||
it('should support decrement', function() {
|
||||
var src = '{% decrement one %}{{one}}';
|
||||
var ctx = {
|
||||
one: 1
|
||||
};
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('0');
|
||||
});
|
||||
it('should support decrement', function () {
|
||||
var src = '{% decrement one %}{{one}}'
|
||||
var ctx = {
|
||||
one: 1
|
||||
}
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('0')
|
||||
})
|
||||
|
||||
it('should decrement undefined', function() {
|
||||
var src = '{% decrement empty %}{{empty}}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('-1');
|
||||
});
|
||||
it('should decrement undefined', function () {
|
||||
var src = '{% decrement empty %}{{empty}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('-1')
|
||||
})
|
||||
|
||||
it('should support decrement multiple times', function() {
|
||||
var src = '{% decrement foo %}{%decrement foo%}{{foo}}';
|
||||
var ctx = {
|
||||
foo: 1
|
||||
};
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('-1');
|
||||
});
|
||||
});
|
||||
it('should support decrement multiple times', function () {
|
||||
var src = '{% decrement foo %}{%decrement foo%}{{foo}}'
|
||||
var ctx = {
|
||||
foo: 1
|
||||
}
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('-1')
|
||||
})
|
||||
})
|
||||
|
||||
+189
-69
@@ -1,82 +1,202 @@
|
||||
const Liquid = require('../..');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/for', function() {
|
||||
var liquid, ctx;
|
||||
before(function() {
|
||||
liquid = Liquid();
|
||||
ctx = {
|
||||
one: 1,
|
||||
alpha: ['a', 'b', 'c'],
|
||||
};
|
||||
});
|
||||
it('should support for', function() {
|
||||
var src = '{%for c in alpha%}{{c}}{%endfor%}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('abc');
|
||||
});
|
||||
describe('tags/for', function () {
|
||||
var liquid, ctx
|
||||
before(function () {
|
||||
liquid = Liquid()
|
||||
liquid.registerTag('throwingTag', {
|
||||
render: function () { throw new Error('intended render error') }
|
||||
})
|
||||
ctx = {
|
||||
one: 1,
|
||||
// eslint-disable-next-line
|
||||
strObj: new String(''),
|
||||
emptyObj: {},
|
||||
nullProtoObj: Object.create(null),
|
||||
obj: {foo: 'bar', coo: 'haa'},
|
||||
alpha: ['a', 'b', 'c'],
|
||||
emptyArray: []
|
||||
}
|
||||
})
|
||||
it('should support array', function () {
|
||||
var src = '{%for c in alpha%}{{c}}{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('abc')
|
||||
})
|
||||
|
||||
it('should throw when for not closed', function() {
|
||||
var src = '{%for c in alpha%}{{c}}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.be.rejectedWith(/tag .* not closed/);
|
||||
});
|
||||
it('should support object', function () {
|
||||
var src = '{%for item in obj%}{{item[0]}},{{item[1]}}-{%else%}b{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('foo,bar-coo,haa-')
|
||||
})
|
||||
|
||||
it('should support for else', function() {
|
||||
var src = '{%for c in ""%}a{%else%}b{%endfor%}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('b');
|
||||
});
|
||||
describe('scope', function () {
|
||||
it('should read super scope', function () {
|
||||
var src = '{%for a in (1..2)%}{{num}}{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, {num: 1}))
|
||||
.to.eventually.equal('11')
|
||||
})
|
||||
it('should write super scope', function () {
|
||||
var src = '{%for a in (1..2)%}{{num}}{%assign num = 2%}{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, {num: 1}))
|
||||
.to.eventually.equal('12')
|
||||
})
|
||||
})
|
||||
|
||||
it('should support for with forloop', function() {
|
||||
var src = '{%for c in alpha%}' +
|
||||
describe('illegal', function () {
|
||||
it('should reject when for not closed', function () {
|
||||
var src = '{%for c in alpha%}{{c}}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.be.rejectedWith(/tag .* not closed/)
|
||||
})
|
||||
|
||||
it('should reject when inner templates rejected', function () {
|
||||
var src = '{%for c in alpha%}{%throwingTag%}{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.be.rejectedWith(/intended render error/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('else', function () {
|
||||
it('should goto else for empty array', function () {
|
||||
var src = '{%for c in emptyArray%}a{%else%}b{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('b')
|
||||
})
|
||||
|
||||
it('should treat non-empty string as one single element', function () {
|
||||
var src = '{%for c in "abc"%}x{{c}}{%else%}y{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('xabc')
|
||||
})
|
||||
|
||||
it('should goto else for empty string', function () {
|
||||
var src = '{%for c in ""%}a{%else%}b{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('b')
|
||||
})
|
||||
|
||||
it('should goto else for empty string object', function () {
|
||||
// it should be false although `new String` is none-conform
|
||||
var src = '{%for c in strObj%}a{%else%}b{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('b')
|
||||
})
|
||||
|
||||
it('should goto else for empty object', function () {
|
||||
var src = '{%for c in emptyObj%}a{%else%}b{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('b')
|
||||
})
|
||||
|
||||
it('should goto else for null-prototyped object', function () {
|
||||
var src = '{%for c in nullProtoObj%}a{%else%}b{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('b')
|
||||
})
|
||||
})
|
||||
|
||||
it('should support for with forloop', function () {
|
||||
var src = '{%for c in alpha%}' +
|
||||
'{{forloop.first}}.{{forloop.index}}.{{forloop.index0}}.' +
|
||||
'{{forloop.last}}.{{forloop.length}}.' +
|
||||
'{{forloop.rindex}}.{{forloop.rindex0}}' +
|
||||
'{{c}}\n' +
|
||||
'{%endfor%}';
|
||||
var dst = 'true.1.0.false.3.3.2a\n' +
|
||||
'{%endfor%}'
|
||||
var dst = 'true.1.0.false.3.3.2a\n' +
|
||||
'false.2.1.false.3.2.1b\n' +
|
||||
'false.3.2.true.3.1.0c\n';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal(dst);
|
||||
});
|
||||
'false.3.2.true.3.1.0c\n'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('should support for with continue', function() {
|
||||
var src = '{% for i in (1..5) %}' +
|
||||
it('should support for with continue', function () {
|
||||
var src = '{% for i in (1..5) %}' +
|
||||
'{{i}}{% continue %}after' +
|
||||
'{% endfor %}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('12345');
|
||||
});
|
||||
it('should support for with break', function() {
|
||||
var src = '{% for i in (one..5) %}' +
|
||||
'{% if i == 4 %}{% break %}{% endif %}' +
|
||||
'{{ i }}' +
|
||||
'{% endfor %}';
|
||||
//return liquid.parseAndRender(src, ctx).catch(e => {
|
||||
//console.log(e.stack);
|
||||
//});
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('123');
|
||||
});
|
||||
'{% endfor %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('12345')
|
||||
})
|
||||
it('should support for with break', function () {
|
||||
var src = '{% for i in (one..5) %}' +
|
||||
'{% if i == 4 %}{% break %}{% endif %}' +
|
||||
'{{ i }}' +
|
||||
'{% endfor %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('123')
|
||||
})
|
||||
|
||||
it('should support for with limit', function() {
|
||||
var src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('12');
|
||||
});
|
||||
it('should support for with limit and offset', function() {
|
||||
var src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('67');
|
||||
});
|
||||
describe('limit', function () {
|
||||
it('should support for with limit', function () {
|
||||
var src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('12')
|
||||
})
|
||||
it('should set forloop.last properly', function () {
|
||||
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.last}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('false true ')
|
||||
})
|
||||
it('should set forloop.first properly', function () {
|
||||
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.first}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('true false ')
|
||||
})
|
||||
it('should set forloop.length properly', function () {
|
||||
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.length}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('2 2 ')
|
||||
})
|
||||
})
|
||||
|
||||
it('should support for reversed', function() {
|
||||
var src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('21');
|
||||
});
|
||||
});
|
||||
describe('offset', function () {
|
||||
it('should support offset with limit', 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 set index properly', function () {
|
||||
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('1 2 ')
|
||||
})
|
||||
it('should set index0 properly', function () {
|
||||
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index0}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('0 1 ')
|
||||
})
|
||||
it('should set rindex properly', function () {
|
||||
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('2 1 ')
|
||||
})
|
||||
it('should set rindex0 properly', function () {
|
||||
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex0}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('1 0 ')
|
||||
})
|
||||
})
|
||||
|
||||
describe('reverse', function () {
|
||||
it('should support for reversed in the last position', function () {
|
||||
var src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('21')
|
||||
})
|
||||
|
||||
it('should support for reversed in the first position', function () {
|
||||
var src = '{% for i in (1..5) reversed limit:2 %}{{ i }}{% endfor %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('21')
|
||||
})
|
||||
|
||||
it('should support for reversed in the middle position', function () {
|
||||
var src = '{% for i in (1..5) offset:2 reversed limit:4 %}{{ i }}{% endfor %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('543')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+113
-47
@@ -1,49 +1,115 @@
|
||||
const Liquid = require('../..');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/if', function() {
|
||||
var liquid = Liquid();
|
||||
var ctx = {
|
||||
one: 1,
|
||||
two: 2,
|
||||
emptyArray: []
|
||||
};
|
||||
describe('tags/if', function () {
|
||||
var liquid = Liquid()
|
||||
var ctx = {
|
||||
one: 1,
|
||||
two: 2,
|
||||
emptyString: '',
|
||||
emptyArray: []
|
||||
}
|
||||
|
||||
it('should support if 1', function() {
|
||||
var src = '{% if false%}yes';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.be.rejectedWith(/tag {% if false%} not closed/);
|
||||
});
|
||||
it('should support if 2', function() {
|
||||
var src = '{%if emptyArray%}a{%endif%}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('');
|
||||
});
|
||||
it('should support if 3', function() {
|
||||
var src = '{% if 2==3 %}yes{%else%}no{%endif%}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no');
|
||||
});
|
||||
it('should support if 4', function() {
|
||||
var src = '{% if 1>=2 and one<two %}a{%endif%}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('');
|
||||
});
|
||||
it('should support if 5', function() {
|
||||
var src = '{% if one!=two %}yes{%else%}no{%endif%}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('yes');
|
||||
});
|
||||
it('should support if 6', function() {
|
||||
var src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('2');
|
||||
});
|
||||
it('should support if 7', function() {
|
||||
var src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}';
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('');
|
||||
});
|
||||
});
|
||||
it('should throw if not closed', function () {
|
||||
var src = '{% if false%}yes'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.be.rejectedWith(/tag {% if false%} not closed/)
|
||||
})
|
||||
it('should support nested', function () {
|
||||
var src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
|
||||
describe('single value as condition', 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')
|
||||
})
|
||||
it('should treat Array truthy', function () {
|
||||
var src = '{%if emptyArray%}a{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('a')
|
||||
})
|
||||
it('should return true if empty string', function () {
|
||||
var src = '{%if emptyString%}a{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('a')
|
||||
})
|
||||
})
|
||||
describe('expression as condition', function () {
|
||||
it('should support ==', function () {
|
||||
var src = '{% if 2==3 %}yes{%else%}no{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
it('should support >=', function () {
|
||||
var src = '{% if 1>=2 and one<two %}a{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
it('should support !=', function () {
|
||||
var src = '{% if one!=two %}yes{%else%}no{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('yes')
|
||||
})
|
||||
it('should support value and expression', function () {
|
||||
var src = `X{%if version and version != '' %}x{{version}}y{%endif%}Y`
|
||||
var ctx = { 'version': '' }
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('XY')
|
||||
})
|
||||
})
|
||||
describe('comparasion to null', function () {
|
||||
it('should evaluate false for null < 10', function () {
|
||||
var src = '{% if null < 10 %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for null > 10', function () {
|
||||
var src = '{% if null > 10 %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for null <= 10', function () {
|
||||
var src = '{% if null <= 10 %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for null >= 10', function () {
|
||||
var src = '{% if null >= 10 %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for 10 < null', function () {
|
||||
var src = '{% if 10 < null %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for 10 > null', function () {
|
||||
var src = '{% if 10 > null %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for 10 <= null', function () {
|
||||
var src = '{% if 10 <= null %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for 10 >= null', function () {
|
||||
var src = '{% if 10 >= null %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+136
-85
@@ -1,92 +1,143 @@
|
||||
const Liquid = require('../..');
|
||||
const mock = require('mock-fs');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
const ParseError = Liquid.Types.ParseError;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const mock = require('mock-fs')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/include', function() {
|
||||
var liquid;
|
||||
before(function() {
|
||||
liquid = Liquid({
|
||||
root: '/',
|
||||
extname: '.html'
|
||||
});
|
||||
});
|
||||
afterEach(function() {
|
||||
mock.restore();
|
||||
});
|
||||
it('should support include', function() {
|
||||
mock({
|
||||
'/current.html': 'bar{% include "bar/foo.html" %}bar',
|
||||
'/bar/foo.html': 'foo'
|
||||
});
|
||||
return expect(liquid.renderFile('/current.html')).to.
|
||||
eventually.equal('barfoobar');
|
||||
});
|
||||
describe('tags/include', function () {
|
||||
var liquid
|
||||
before(function () {
|
||||
liquid = Liquid({
|
||||
root: '/',
|
||||
extname: '.html'
|
||||
})
|
||||
})
|
||||
afterEach(function () {
|
||||
mock.restore()
|
||||
})
|
||||
it('should support include', function () {
|
||||
mock({
|
||||
'/current.html': 'bar{% include "bar/foo.html" %}bar',
|
||||
'/bar/foo.html': 'foo'
|
||||
})
|
||||
return expect(liquid.renderFile('/current.html')).to
|
||||
.eventually.equal('barfoobar')
|
||||
})
|
||||
|
||||
it('should throw when illegal', function() {
|
||||
mock({
|
||||
'/illegal.html': '{%include%}',
|
||||
});
|
||||
return liquid.renderFile('/illegal.html').catch(function(e){
|
||||
expect(e.name).to.equal('ParseError');
|
||||
expect(e.message).to.match(/illegal token {%include%}/);
|
||||
});
|
||||
});
|
||||
it('should throw when not specified', function () {
|
||||
mock({
|
||||
'/parent.html': '{%include%}'
|
||||
})
|
||||
return liquid.renderFile('/parent.html').catch(function (e) {
|
||||
expect(e.name).to.equal('RenderError')
|
||||
expect(e.message).to.match(/cannot include with empty filename/)
|
||||
})
|
||||
})
|
||||
|
||||
it('should support include with relative path', function() {
|
||||
mock({
|
||||
'/bar/foo.html': 'foo',
|
||||
'/foo/relative.html': 'bar{% include "../bar/foo.html" %}bar',
|
||||
});
|
||||
return expect(liquid.renderFile('foo/relative.html')).to.
|
||||
eventually.equal('barfoobar');
|
||||
});
|
||||
it('should throw when not exist', function () {
|
||||
mock({
|
||||
'/parent.html': '{%include not-exist%}'
|
||||
})
|
||||
return liquid.renderFile('/parent.html').catch(function (e) {
|
||||
expect(e.name).to.equal('RenderError')
|
||||
expect(e.message).to.match(/cannot include with empty filename/)
|
||||
})
|
||||
})
|
||||
|
||||
it('should support include: hash list', function() {
|
||||
mock({
|
||||
'/hash.html': '{% assign name="harttle" %}{% include "user.html", role: "admin", alias: name %}',
|
||||
'/user.html': '{{name}} : {{role}} : {{alias}}',
|
||||
});
|
||||
return expect(liquid.renderFile('hash.html')).to.
|
||||
eventually.equal('harttle : admin : harttle');
|
||||
});
|
||||
it('should support include with relative path', function () {
|
||||
mock({
|
||||
'/bar/foo.html': 'foo',
|
||||
'/foo/relative.html': 'bar{% include "../bar/foo.html" %}bar'
|
||||
})
|
||||
return expect(liquid.renderFile('foo/relative.html')).to
|
||||
.eventually.equal('barfoobar')
|
||||
})
|
||||
|
||||
it('should support include: parent scope', function() {
|
||||
mock({
|
||||
'/scope.html': '{% assign shape="triangle" %}{% assign color="yellow" %}{% include "color.html" %}',
|
||||
'/color.html': 'color:{{color}}, shape:{{shape}}',
|
||||
});
|
||||
return expect(liquid.renderFile('scope.html')).to.
|
||||
eventually.equal('color:yellow, shape:triangle');
|
||||
});
|
||||
it('should support include: hash list', function () {
|
||||
mock({
|
||||
'/hash.html': '{% assign name="harttle" %}{% include "user.html", role: "admin", alias: name %}',
|
||||
'/user.html': '{{name}} : {{role}} : {{alias}}'
|
||||
})
|
||||
return expect(liquid.renderFile('hash.html')).to
|
||||
.eventually.equal('harttle : admin : harttle')
|
||||
})
|
||||
|
||||
it('should support include: with', function() {
|
||||
mock({
|
||||
'/with.html': '{% include "color" with "red", shape: "rect" %}',
|
||||
'/color.html': 'color:{{color}}, shape:{{shape}}',
|
||||
});
|
||||
return expect(liquid.renderFile('with.html')).to.
|
||||
eventually.equal('color:red, shape:rect');
|
||||
});
|
||||
it('should support include: parent scope', function () {
|
||||
mock({
|
||||
'/scope.html': '{% assign shape="triangle" %}{% assign color="yellow" %}{% include "color.html" %}',
|
||||
'/color.html': 'color:{{color}}, shape:{{shape}}'
|
||||
})
|
||||
return expect(liquid.renderFile('scope.html')).to
|
||||
.eventually.equal('color:yellow, shape:triangle')
|
||||
})
|
||||
|
||||
it('should support nested includes', function() {
|
||||
mock({
|
||||
'/personInfo.html': 'This is a person {% include "card.html" %}',
|
||||
'/card.html': '<p>{{person.firstName}} {{person.lastName}}<br/>{% include "address" %}</p>',
|
||||
'/address.html': 'City: {{person.address.city}}'
|
||||
});
|
||||
var ctx = {
|
||||
person: {
|
||||
firstName: 'Joe',
|
||||
lastName: 'Shmoe',
|
||||
address: {
|
||||
city: 'Dallas'
|
||||
}
|
||||
}
|
||||
};
|
||||
return expect(liquid.renderFile('personInfo.html', ctx)).to.
|
||||
eventually.equal('This is a person <p>Joe Shmoe<br/>City: Dallas</p>');
|
||||
});
|
||||
});
|
||||
it('should support include: with', function () {
|
||||
mock({
|
||||
'/with.html': '{% include "color" with "red", shape: "rect" %}',
|
||||
'/color.html': 'color:{{color}}, shape:{{shape}}'
|
||||
})
|
||||
return expect(liquid.renderFile('with.html')).to
|
||||
.eventually.equal('color:red, shape:rect')
|
||||
})
|
||||
|
||||
it('should support nested includes', function () {
|
||||
mock({
|
||||
'/personInfo.html': 'This is a person {% include "card.html" %}',
|
||||
'/card.html': '<p>{{person.firstName}} {{person.lastName}}<br/>{% include "address" %}</p>',
|
||||
'/address.html': 'City: {{person.address.city}}'
|
||||
})
|
||||
var ctx = {
|
||||
person: {
|
||||
firstName: 'Joe',
|
||||
lastName: 'Shmoe',
|
||||
address: {
|
||||
city: 'Dallas'
|
||||
}
|
||||
}
|
||||
}
|
||||
return expect(liquid.renderFile('personInfo.html', ctx)).to
|
||||
.eventually.equal('This is a person <p>Joe Shmoe<br/>City: Dallas</p>')
|
||||
})
|
||||
|
||||
describe('static partial', function () {
|
||||
it('should support filename with extention', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{% include child.html color:"red" %}Y',
|
||||
'/child.html': 'child with {{color}}'
|
||||
})
|
||||
var staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
|
||||
return expect(staticLiquid.renderFile('parent.html')).to
|
||||
.eventually.equal('Xchild with redY')
|
||||
})
|
||||
|
||||
it('should support parent paths', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{% include bar/./../foo/child.html %}Y',
|
||||
'/foo/child.html': 'child'
|
||||
})
|
||||
var staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
|
||||
return expect(staticLiquid.renderFile('parent.html')).to
|
||||
.eventually.equal('XchildY')
|
||||
})
|
||||
|
||||
it('should support subpaths', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{% include foo/child.html %}Y',
|
||||
'/foo/child.html': 'child'
|
||||
})
|
||||
var staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
|
||||
return expect(staticLiquid.renderFile('parent.html')).to
|
||||
.eventually.equal('XchildY')
|
||||
})
|
||||
|
||||
it('should support comma separated arguments', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{% include child.html, color:"red" %}Y',
|
||||
'/child.html': 'child with {{color}}'
|
||||
})
|
||||
var staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
|
||||
return expect(staticLiquid.renderFile('parent.html')).to
|
||||
.eventually.equal('Xchild with redY')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+28
-28
@@ -1,32 +1,32 @@
|
||||
const Liquid = require('../..');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/increment', function() {
|
||||
var liquid = Liquid();
|
||||
describe('tags/increment', function () {
|
||||
var liquid = Liquid()
|
||||
|
||||
it('should support increment', function() {
|
||||
var src = '{% increment one %}{{one}}';
|
||||
var ctx = {
|
||||
one: 1
|
||||
};
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('2');
|
||||
});
|
||||
it('should support increment', function () {
|
||||
var src = '{% increment one %}{{one}}'
|
||||
var ctx = {
|
||||
one: 1
|
||||
}
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('2')
|
||||
})
|
||||
|
||||
it('should increment undefined', function() {
|
||||
var src = '{% increment empty %}{{empty}}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('1');
|
||||
});
|
||||
it('should increment undefined', function () {
|
||||
var src = '{% increment empty %}{{empty}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('1')
|
||||
})
|
||||
|
||||
it('should support increment multiple times', function() {
|
||||
var src = '{% increment foo %}{%increment foo%}{{foo}}';
|
||||
var ctx = {
|
||||
foo: 1
|
||||
};
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('3');
|
||||
});
|
||||
});
|
||||
it('should support increment multiple times', function () {
|
||||
var src = '{% increment foo %}{%increment foo%}{{foo}}'
|
||||
var ctx = {
|
||||
foo: 1
|
||||
}
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('3')
|
||||
})
|
||||
})
|
||||
|
||||
+138
-79
@@ -1,81 +1,140 @@
|
||||
const Liquid = require('../..');
|
||||
const mock = require('mock-fs');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const mock = require('mock-fs')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/layout', function() {
|
||||
var liquid;
|
||||
before(function() {
|
||||
liquid = Liquid({
|
||||
root: '/',
|
||||
extname: '.html'
|
||||
});
|
||||
});
|
||||
afterEach(function() {
|
||||
mock.restore();
|
||||
});
|
||||
describe('tags/layout', function () {
|
||||
var liquid
|
||||
before(function () {
|
||||
liquid = Liquid({
|
||||
root: '/',
|
||||
extname: '.html'
|
||||
})
|
||||
})
|
||||
afterEach(function () {
|
||||
mock.restore()
|
||||
})
|
||||
|
||||
it('should throw when block not closed', function() {
|
||||
mock({
|
||||
'/parent.html': 'parent',
|
||||
});
|
||||
src = '{% layout "parent" %}{%block%}A';
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.be.rejectedWith(/tag {%block%} not closed/);
|
||||
});
|
||||
it('should handle anonymous block', function() {
|
||||
mock({
|
||||
'/parent.html': 'X{%block%}{%endblock%}Y',
|
||||
});
|
||||
src = '{% layout "parent.html" %}{%block%}A{%endblock%}';
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.eventually.equal('XAY');
|
||||
});
|
||||
it('should handle named blocks', function() {
|
||||
mock({
|
||||
'/parent.html': 'X{% block "a"%}{% endblock %}Y{% block b%}{%endblock%}Z',
|
||||
});
|
||||
src = '{% layout "parent.html" %}' +
|
||||
'{%block a%}A{%endblock%}' +
|
||||
'{%block b%}B{%endblock%}';
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.eventually.equal('XAYBZ');
|
||||
});
|
||||
it('should support default block content', function() {
|
||||
mock({
|
||||
'/parent.html': 'X{% block "a"%}A{% endblock %}Y{% block b%}B{%endblock%}Z',
|
||||
});
|
||||
src = '{% layout "parent.html" %}{%block a%}a{%endblock%}';
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.eventually.equal('XaYBZ');
|
||||
});
|
||||
it('should handle nested block', function() {
|
||||
mock({
|
||||
'/grand.html': 'X{%block a%}G{%endblock%}Y',
|
||||
'/parent.html': '{%layout "grand" %}{%block a%}P{%endblock%}',
|
||||
'/main.html': '{%layout "parent"%}{%block a%}A{%endblock%}'
|
||||
})
|
||||
return expect(liquid.renderFile('/main.html')).to
|
||||
.eventually.equal('XAY');
|
||||
});
|
||||
it('should not bleed scope into included layout', function() {
|
||||
mock({
|
||||
'/parent.html': 'X{%block a%}{%endblock%}Y{%block b%}{%endblock%}Z',
|
||||
'/main.html': '{%layout "parent"%}'+
|
||||
'{%block a%}A{%endblock%}' +
|
||||
'{%block b%}I{%include "included"%}J{%endblock%}',
|
||||
'/included.html': '{%layout "parent"%}{%block a%}a{%endblock%}'
|
||||
})
|
||||
return expect(liquid.renderFile('main')).to
|
||||
.eventually.equal('XAYIXaYZJZ');
|
||||
});
|
||||
it('should support hash list', function() {
|
||||
mock({
|
||||
'/parent.html': '{{color}}{%block%}{%endblock%}',
|
||||
'/main.html': '{% layout "parent.html" color:"black"%}{%block%}A{%endblock%}'
|
||||
});
|
||||
return expect(liquid.renderFile('/main.html')).to.
|
||||
eventually.equal('blackA');
|
||||
});
|
||||
});
|
||||
it('should throw when block not closed', function () {
|
||||
mock({
|
||||
'/parent.html': 'parent'
|
||||
})
|
||||
var src = '{% layout "parent" %}{%block%}A'
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.be.rejectedWith(/tag {%block%} not closed/)
|
||||
})
|
||||
it('should throw when filename not specified', function () {
|
||||
mock({
|
||||
'/parent.html': '{%layout%}'
|
||||
})
|
||||
return liquid.renderFile('/parent.html').catch(function (e) {
|
||||
expect(e.name).to.equal('RenderError')
|
||||
expect(e.message).to.match(/cannot apply layout with empty filename/)
|
||||
})
|
||||
})
|
||||
describe('anonymous block', function () {
|
||||
it('should handle anonymous block', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{%block%}{%endblock%}Y'
|
||||
})
|
||||
var src = '{% layout "parent.html" %}{%block%}A{%endblock%}'
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.eventually.equal('XAY')
|
||||
})
|
||||
it('should handle top level contents as anonymous block', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{%block%}{%endblock%}Y'
|
||||
})
|
||||
var src = '{% layout "parent.html" %}A'
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.eventually.equal('XAY')
|
||||
})
|
||||
})
|
||||
it('should handle named blocks', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{% block "a"%}{% endblock %}Y{% block b%}{%endblock%}Z'
|
||||
})
|
||||
var src = '{% layout "parent.html" %}' +
|
||||
'{%block a%}A{%endblock%}' +
|
||||
'{%block b%}B{%endblock%}'
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.eventually.equal('XAYBZ')
|
||||
})
|
||||
it('should support default block content', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{% block "a"%}A{% endblock %}Y{% block b%}B{%endblock%}Z'
|
||||
})
|
||||
var src = '{% layout "parent.html" %}{%block a%}a{%endblock%}'
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.eventually.equal('XaYBZ')
|
||||
})
|
||||
it('should handle nested block', function () {
|
||||
mock({
|
||||
'/grand.html': 'X{%block a%}G{%endblock%}Y',
|
||||
'/parent.html': '{%layout "grand" %}{%block a%}P{%endblock%}',
|
||||
'/main.html': '{%layout "parent"%}{%block a%}A{%endblock%}'
|
||||
})
|
||||
return expect(liquid.renderFile('/main.html')).to
|
||||
.eventually.equal('XAY')
|
||||
})
|
||||
it('should not bleed scope into included layout', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{%block a%}{%endblock%}Y{%block b%}{%endblock%}Z',
|
||||
'/main.html': '{%layout "parent"%}' +
|
||||
'{%block a%}A{%endblock%}' +
|
||||
'{%block b%}I{%include "included"%}J{%endblock%}',
|
||||
'/included.html': '{%layout "parent"%}{%block a%}a{%endblock%}'
|
||||
})
|
||||
return expect(liquid.renderFile('main')).to
|
||||
.eventually.equal('XAYIXaYZJZ')
|
||||
})
|
||||
it('should support hash list', function () {
|
||||
mock({
|
||||
'/parent.html': '{{color}}{%block%}{%endblock%}',
|
||||
'/main.html': '{% layout "parent.html" color:"black"%}{%block%}A{%endblock%}'
|
||||
})
|
||||
return expect(liquid.renderFile('/main.html')).to
|
||||
.eventually.equal('blackA')
|
||||
})
|
||||
it('should support multiple hash', function () {
|
||||
mock({
|
||||
'/parent.html': '{{color}}{{bg}}{%block%}{%endblock%}',
|
||||
'/main.html': '{% layout "parent.html" color:"black", bg:"red"%}{%block%}A{%endblock%}'
|
||||
})
|
||||
return expect(liquid.renderFile('/main.html')).to
|
||||
.eventually.equal('blackredA')
|
||||
})
|
||||
|
||||
describe('static partial', function () {
|
||||
it('should support filename with extention', function () {
|
||||
mock({
|
||||
'/parent.html': '{{color}}{%block%}{%endblock%}',
|
||||
'/main.html': '{% layout parent.html color:"black"%}{%block%}A{%endblock%}'
|
||||
})
|
||||
var staticLiquid = Liquid({ root: '/', dynamicPartials: false })
|
||||
return expect(staticLiquid.renderFile('/main.html')).to
|
||||
.eventually.equal('blackA')
|
||||
})
|
||||
|
||||
it('should support parent paths', function () {
|
||||
mock({
|
||||
'/foo/parent.html': '{{color}}{%block%}{%endblock%}',
|
||||
'/main.html': '{% layout bar/../foo/parent.html color:"black"%}{%block%}A{%endblock%}'
|
||||
})
|
||||
var staticLiquid = Liquid({ root: '/', dynamicPartials: false })
|
||||
return expect(staticLiquid.renderFile('/main.html')).to
|
||||
.eventually.equal('blackA')
|
||||
})
|
||||
|
||||
it('should support subpaths', function () {
|
||||
mock({
|
||||
'/foo/parent.html': '{{color}}{%block%}{%endblock%}',
|
||||
'/main.html': '{% layout foo/parent.html color:"black"%}{%block%}A{%endblock%}'
|
||||
})
|
||||
var staticLiquid = Liquid({ root: '/', dynamicPartials: false })
|
||||
return expect(staticLiquid.renderFile('/main.html')).to
|
||||
.eventually.equal('blackA')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+23
-23
@@ -1,24 +1,24 @@
|
||||
const Liquid = require('../..');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/raw', function() {
|
||||
var liquid = Liquid();
|
||||
it('should support raw 1', function() {
|
||||
return expect(liquid.parseAndRender('{% raw%}'))
|
||||
.to.be.rejectedWith(/{% raw%} not closed/);
|
||||
});
|
||||
it('should support raw 2', function() {
|
||||
var src = '{% raw %}{{ 5 | plus: 6 }}{% endraw %} is equal to 11.';
|
||||
var dst = '{{ 5 | plus: 6 }} is equal to 11.';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal(dst);
|
||||
});
|
||||
it('should support raw 3', function() {
|
||||
var src = '{% raw %}\n{{ foo}} \n{% endraw %}';
|
||||
var dst = '\n{{ foo}} \n';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal(dst);
|
||||
});
|
||||
});
|
||||
describe('tags/raw', function () {
|
||||
var liquid = Liquid()
|
||||
it('should support raw 1', function () {
|
||||
return expect(liquid.parseAndRender('{% raw%}'))
|
||||
.to.be.rejectedWith(/{% raw%} not closed/)
|
||||
})
|
||||
it('should support raw 2', function () {
|
||||
var src = '{% raw %}{{ 5 | plus: 6 }}{% endraw %} is equal to 11.'
|
||||
var dst = '{{ 5 | plus: 6 }} is equal to 11.'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal(dst)
|
||||
})
|
||||
it('should support raw 3', function () {
|
||||
var src = '{% raw %}\n{{ foo}} \n{% endraw %}'
|
||||
var dst = '\n{{ foo}} \n'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal(dst)
|
||||
})
|
||||
})
|
||||
|
||||
+64
-62
@@ -1,70 +1,72 @@
|
||||
const Liquid = require('../..');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/tablerow', function() {
|
||||
var liquid = Liquid();
|
||||
describe('tags/tablerow', function () {
|
||||
var liquid = Liquid()
|
||||
|
||||
it('should support tablerow', function() {
|
||||
var src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}';
|
||||
var ctx = {
|
||||
alpha: ['a', 'b', 'c']
|
||||
};
|
||||
var dst = '<table>' +
|
||||
'<tr class="row1"><td class="col1">a</td><td class="col2">b</td></tr>' +
|
||||
'<tr class="row2"><td class="col1">c</td></tr>' +
|
||||
'</table>';
|
||||
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst);
|
||||
});
|
||||
it('should support tablerow', function () {
|
||||
var src = '{% tablerow i in (1..3)%}{{ i }}{% endtablerow %}'
|
||||
var dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('should support empty tablerow', function() {
|
||||
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}';
|
||||
var dst = '<table></table>';
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst);
|
||||
});
|
||||
it('should support cols', function () {
|
||||
var src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}'
|
||||
var ctx = {
|
||||
alpha: ['a', 'b', 'c']
|
||||
}
|
||||
var dst =
|
||||
'<tr class="row1"><td class="col1">a</td><td class="col2">b</td></tr>' +
|
||||
'<tr class="row2"><td class="col1">c</td></tr>'
|
||||
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('should throw when tablerow not closed', function() {
|
||||
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/tag .* not closed/);
|
||||
});
|
||||
it('should support cols set to 0', function () {
|
||||
var src = '{% tablerow i in (1..3) cols:0 %}{{ i }}{% endtablerow %}'
|
||||
var dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('should support tablerow with range', function() {
|
||||
var src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}';
|
||||
var dst = '<table>' +
|
||||
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
|
||||
'<tr class="row2"><td class="col1">3</td><td class="col2">4</td></tr>' +
|
||||
'<tr class="row3"><td class="col1">5</td></tr>' +
|
||||
'</table>';
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst);
|
||||
});
|
||||
it('should support empty tablerow', function () {
|
||||
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}'
|
||||
var dst = ''
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('tablerow should throw on illegal cols 1', function() {
|
||||
var src = '{% tablerow i in (1..5) cols:0 %}{{ i }}{% endtablerow %}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/illegal cols: 0/);
|
||||
});
|
||||
it('tablerow should throw on illegal cols 2', function() {
|
||||
var src = '{% tablerow i in (1..5) %}{{ i }}{% endtablerow %}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/illegal cols: undefined/);
|
||||
});
|
||||
it('should support empty array', function () {
|
||||
var src = '{% tablerow i in alpha.z cols:2 %}{{ i }}{% endtablerow %}'
|
||||
var dst = ''
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('should support tablerow with limit', function() {
|
||||
var src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}';
|
||||
var dst = '<table>' +
|
||||
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
|
||||
'<tr class="row2"><td class="col1">3</td></tr>' +
|
||||
'</table>';
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst);
|
||||
});
|
||||
it('should throw when tablerow not closed', function () {
|
||||
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/tag .* not closed/)
|
||||
})
|
||||
|
||||
it('should support tablerow with offset', function() {
|
||||
var src = '{% tablerow i in (1..5) cols:2 offset:3 %}{{ i }}{% endtablerow %}';
|
||||
var dst = '<table>' +
|
||||
'<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>' +
|
||||
'</table>';
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst);
|
||||
});
|
||||
});
|
||||
it('should support tablerow with range', function () {
|
||||
var src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}'
|
||||
var dst =
|
||||
'<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>'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('should support tablerow with limit', function () {
|
||||
var src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}'
|
||||
var dst =
|
||||
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
|
||||
'<tr class="row2"><td class="col1">3</td></tr>'
|
||||
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 = '<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
})
|
||||
|
||||
+33
-32
@@ -1,34 +1,35 @@
|
||||
const Liquid = require('../..');
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
const Liquid = require('../..')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/unless', function() {
|
||||
var liquid = Liquid();
|
||||
describe('tags/unless', function () {
|
||||
var liquid = Liquid()
|
||||
|
||||
it('should render else when predicate yields true', function() {
|
||||
var src = '{% unless 1 %}yes{%else%}no{%endunless%}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('no');
|
||||
});
|
||||
it('should render unless when predicate yields false', function() {
|
||||
var src = '{% unless 0 %}yes{%else%}no{%endunless%}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('yes');
|
||||
});
|
||||
it('should reject when tag not closed', function() {
|
||||
var src = '{% unless 1>2 %}yes';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/tag {% unless 1>2 %} not closed/);
|
||||
});
|
||||
it('should render unless when predicate yields false and else undefined', function() {
|
||||
var src = '{% unless 1>2 %}yes{%endunless%}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('yes');
|
||||
});
|
||||
it('should render "" when predicate yields false and else undefined', function() {
|
||||
var src = '{% unless 1<2 %}yes{%endunless%}';
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('');
|
||||
});
|
||||
});
|
||||
it('should render else when predicate yields true', function () {
|
||||
// 0 is truthy
|
||||
var src = '{% unless 0 %}yes{%else%}no{%endunless%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
it('should render unless when predicate yields false', function () {
|
||||
var src = '{% unless false %}yes{%else%}no{%endunless%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('yes')
|
||||
})
|
||||
it('should reject when tag not closed', function () {
|
||||
var src = '{% unless 1>2 %}yes'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/tag {% unless 1>2 %} not closed/)
|
||||
})
|
||||
it('should render unless when predicate yields false and else undefined', function () {
|
||||
var src = '{% unless 1>2 %}yes{%endunless%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('yes')
|
||||
})
|
||||
it('should render "" when predicate yields false and else undefined', function () {
|
||||
var src = '{% unless 1<2 %}yes{%endunless%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
})
|
||||
|
||||
+66
-51
@@ -1,57 +1,72 @@
|
||||
var chai = require("chai");
|
||||
var should = chai.should();
|
||||
var expect = chai.expect;
|
||||
const chai = require('chai')
|
||||
const parse = require('../src/tokenizer.js').parse
|
||||
const expect = chai.expect
|
||||
|
||||
var tokenizer = require('../src/tokenizer.js');
|
||||
describe('tokenizer', function () {
|
||||
describe('parse', function () {
|
||||
it('should handle plain HTML', function () {
|
||||
var html = '<html><body><p>Lorem Ipsum</p></body></html>'
|
||||
var tokens = parse(html)
|
||||
|
||||
describe('tokenizer', function() {
|
||||
it('should handle plain HTML', function() {
|
||||
var html = '<html><body><p>Lorem Ipsum</p></body></html>';
|
||||
var tokens = tokenizer.parse(html);
|
||||
expect(tokens.length).to.equal(1)
|
||||
expect(tokens[0].value).to.equal(html)
|
||||
expect(tokens[0].type).to.equal('html')
|
||||
})
|
||||
it('should throw when non-string passed in', function () {
|
||||
expect(function () {
|
||||
parse({})
|
||||
}).to.throw('illegal input')
|
||||
})
|
||||
it('should handle tag syntax', function () {
|
||||
var html = '<p>{% for p in a[1]%}</p>'
|
||||
var tokens = parse(html)
|
||||
|
||||
tokens.length.should.equal(1);
|
||||
tokens[0].value.should.equal(html);
|
||||
tokens[0].type.should.equal('html');
|
||||
});
|
||||
it('should throw when non-string passed in', function() {
|
||||
expect(function() {
|
||||
tokenizer.parse({});
|
||||
}).to.throw('illegal input type');
|
||||
});
|
||||
it('should handle tag syntax', function() {
|
||||
var html = '<p>{% for p in a[1]%}</p>';
|
||||
var tokens = tokenizer.parse(html);
|
||||
expect(tokens.length).to.equal(3)
|
||||
expect(tokens[1].type).to.equal('tag')
|
||||
expect(tokens[1].value).to.equal('for p in a[1]')
|
||||
})
|
||||
it('should handle value syntax', function () {
|
||||
var html = '<p>{{foo | date: "%Y-%m-%d"}}</p>'
|
||||
var tokens = parse(html)
|
||||
|
||||
tokens.length.should.equal(3);
|
||||
tokens[1].type.should.equal('tag');
|
||||
tokens[1].value.should.equal('for p in a[1]');
|
||||
});
|
||||
it('should handle output syntax', function() {
|
||||
var html = '<p>{{foo | date: "%Y-%m-%d"}}</p>';
|
||||
var tokens = tokenizer.parse(html);
|
||||
expect(tokens.length).to.equal(3)
|
||||
expect(tokens[1].type).to.equal('value')
|
||||
expect(tokens[1].value).to.equal('foo | date: "%Y-%m-%d"')
|
||||
})
|
||||
it('should handle consecutive value and tags', function () {
|
||||
var html = '{{foo}}{{bar}}{%foo%}{%bar%}'
|
||||
var tokens = parse(html)
|
||||
|
||||
tokens.length.should.equal(3);
|
||||
tokens[1].type.should.equal('output');
|
||||
tokens[1].value.should.equal('foo | date: "%Y-%m-%d"');
|
||||
});
|
||||
it('should handle successive outputs and tags', function() {
|
||||
var html = '{{foo}}{{bar}}{%foo%}{%bar%}';
|
||||
var tokens = tokenizer.parse(html);
|
||||
expect(tokens.length).to.equal(4)
|
||||
expect(tokens[0].type).to.equal('value')
|
||||
expect(tokens[3].type).to.equal('tag')
|
||||
|
||||
tokens.length.should.equal(4);
|
||||
tokens[0].type.should.equal('output');
|
||||
tokens[3].type.should.equal('tag');
|
||||
|
||||
tokens[1].value.should.equal('bar');
|
||||
tokens[2].value.should.equal('foo');
|
||||
});
|
||||
it('should keep white spaces and newlines', function() {
|
||||
var html = '{{foo}}\n{%bar %} \n {{alice}}';
|
||||
var tokens = tokenizer.parse(html);
|
||||
expect(tokens.length).to.equal(5);
|
||||
expect(tokens[1].type).to.equal('html');
|
||||
expect(tokens[1].raw).to.equal('\n');
|
||||
expect(tokens[3].type).to.equal('html');
|
||||
expect(tokens[3].raw).to.equal(' \n ');
|
||||
});
|
||||
});
|
||||
expect(tokens[1].value).to.equal('bar')
|
||||
expect(tokens[2].value).to.equal('foo')
|
||||
})
|
||||
it('should keep white spaces and newlines', function () {
|
||||
var html = '{%foo%}\n{%bar %} \n {%alice%}'
|
||||
var tokens = parse(html)
|
||||
expect(tokens.length).to.equal(5)
|
||||
expect(tokens[1].type).to.equal('html')
|
||||
expect(tokens[1].raw).to.equal('\n')
|
||||
expect(tokens[3].type).to.equal('html')
|
||||
expect(tokens[3].raw).to.equal(' \n ')
|
||||
})
|
||||
it('should handle multiple lines tag', function () {
|
||||
var html = '{%foo\na:a\nb:1.23\n%}'
|
||||
var tokens = parse(html)
|
||||
expect(tokens.length).to.equal(1)
|
||||
expect(tokens[0].type).to.equal('tag')
|
||||
expect(tokens[0].args).to.equal('a:a\nb:1.23')
|
||||
expect(tokens[0].raw).to.equal('{%foo\na:a\nb:1.23\n%}')
|
||||
})
|
||||
it('should handle multiple lines 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('value')
|
||||
expect(tokens[0].raw).to.equal('{{foo\n|date:\n"%Y-%m-%d"\n}}')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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/)
|
||||
})
|
||||
})
|
||||
+378
-309
@@ -1,322 +1,391 @@
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
const mock = require('mock-fs');
|
||||
chai.use(require("chai-as-promised"));
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
const mock = require('mock-fs')
|
||||
const path = require('path')
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
var engine = require('../..')();
|
||||
var engine = require('../..')()
|
||||
var strictEngine = require('../..')({
|
||||
strict_variables: true,
|
||||
strict_filters: true
|
||||
});
|
||||
strict_variables: true,
|
||||
strict_filters: true
|
||||
})
|
||||
|
||||
describe('error', function() {
|
||||
describe('error', function () {
|
||||
afterEach(function () {
|
||||
mock.restore()
|
||||
})
|
||||
|
||||
describe('TokenizationError', function() {
|
||||
it('should throw TokenizationError when tag illegal', function() {
|
||||
return expect(engine.parseAndRender('{% . a %}', {})).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.name).to.equal('TokenizationError');
|
||||
expect(err.message).to.contain('illegal tag syntax');
|
||||
});
|
||||
});
|
||||
it('should contain template content in err.message', function() {
|
||||
var html = ['1st', '2nd', 'X{% . a %} Y', '4th'];
|
||||
var message = [
|
||||
'illegal tag syntax',
|
||||
' 1| 1st',
|
||||
' 2| 2nd',
|
||||
'>> 3| X{% . a %} Y',
|
||||
' 4| 4th'
|
||||
];
|
||||
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.message).to.equal(message.join('\n'));
|
||||
expect(err.name).to.equal('TokenizationError');
|
||||
});
|
||||
});
|
||||
it('should contain the whole template content in err.input', function() {
|
||||
var html = 'bar\nfoo{% . a %}\nfoo';
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.input).to.equal(html);
|
||||
});
|
||||
});
|
||||
it('should contain line number in err.line', function() {
|
||||
return expect(engine.parseAndRender('1\n2\n{% . a %}\n4', {})).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.name).to.equal('TokenizationError');
|
||||
expect(err.line).to.equal(3);
|
||||
});
|
||||
});
|
||||
it('should contain stack in err.stack', function() {
|
||||
return expect(engine.parseAndRender('{% . a %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.stack).to.contain('illegal tag syntax');
|
||||
expect(err.stack).to.contain('at Object.parse');
|
||||
});
|
||||
});
|
||||
it('should contain file path in err.file', function() {
|
||||
var html = '<html>\n<head>\n\n{% . a %}\n\n';
|
||||
mock({
|
||||
"/foo.html": html
|
||||
});
|
||||
return expect(engine.renderFile('/foo.html')).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
mock.restore();
|
||||
expect(err.name).to.equal('TokenizationError');
|
||||
expect(err.file).to.equal('/foo.html');
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('TokenizationError', function () {
|
||||
it('should throw TokenizationError when tag illegal', function () {
|
||||
return expect(engine.parseAndRender('{% . a %}', {})).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('TokenizationError')
|
||||
expect(err.message).to.contain('illegal tag syntax')
|
||||
})
|
||||
})
|
||||
it('should contain template content in err.message', function () {
|
||||
var html = ['1st', '2nd', 'X{% . a %} Y', '4th']
|
||||
var message = [
|
||||
' 1| 1st',
|
||||
' 2| 2nd',
|
||||
'>> 3| X{% . a %} Y',
|
||||
' 4| 4th',
|
||||
'TokenizationError'
|
||||
]
|
||||
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.equal('illegal tag syntax, line:3')
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('TokenizationError')
|
||||
})
|
||||
})
|
||||
it('should contain the whole template content in err.input', function () {
|
||||
var html = 'bar\nfoo{% . a %}\nfoo'
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.input).to.equal(html)
|
||||
})
|
||||
})
|
||||
it('should contain line number in err.line', function () {
|
||||
return expect(engine.parseAndRender('1\n2\n{% . a %}\n4', {})).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('TokenizationError')
|
||||
expect(err.line).to.equal(3)
|
||||
})
|
||||
})
|
||||
it('should contain stack in err.stack', function () {
|
||||
return expect(engine.parseAndRender('{% . a %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.contain('illegal tag syntax')
|
||||
expect(err.stack).to.contain('at Object.parse')
|
||||
})
|
||||
})
|
||||
describe('captureStackTrace compatibility', function () {
|
||||
var captureStackTrace = Error.captureStackTrace
|
||||
before(() => (Error.captureStackTrace = null))
|
||||
after(() => (Error.captureStackTrace = captureStackTrace))
|
||||
it('should use empty string if captureStackTrace not defined', function () {
|
||||
return expect(engine.parseAndRender('{% . a %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.stack).to.contain('illegal tag syntax')
|
||||
expect(err.stack).to.not.contain('at Object.parse')
|
||||
})
|
||||
})
|
||||
})
|
||||
it('should contain file path in err.file', function () {
|
||||
var html = '<html>\n<head>\n\n{% . a %}\n\n'
|
||||
mock({
|
||||
'/foo.html': html
|
||||
})
|
||||
return expect(engine.renderFile('/foo.html')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
mock.restore()
|
||||
expect(err.name).to.equal('TokenizationError')
|
||||
expect(err.file).to.equal(path.resolve('/foo.html'))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('RenderError', function() {
|
||||
beforeEach(function() {
|
||||
engine = require('../..')();
|
||||
engine.registerTag('throwingTag', {
|
||||
render: function() {
|
||||
throw new Error('intended render error');
|
||||
}
|
||||
});
|
||||
engine.registerTag('rejectingTag', {
|
||||
render: function() {
|
||||
return Promise.reject(new Error('intended render reject'));
|
||||
}
|
||||
});
|
||||
engine.registerFilter('throwingFilter', () => {
|
||||
throw new Error('throwed by filter');
|
||||
});
|
||||
});
|
||||
it('should throw RenderError when tag throws', function() {
|
||||
var src = '{%throwingTag%}';
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.name).to.equal('RenderError');
|
||||
expect(err.message).to.contain('intended render error');
|
||||
});
|
||||
});
|
||||
it('should throw RenderError when tag rejects', function() {
|
||||
var src = '{%rejectingTag%}';
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.name).to.equal('RenderError');
|
||||
expect(err.message).to.contain('intended render reject');
|
||||
});
|
||||
});
|
||||
it('should throw RenderError when filter throws', function() {
|
||||
var src = '{{1|throwingFilter}}';
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.name).to.equal('RenderError');
|
||||
expect(err.message).to.contain('throwed by filter');
|
||||
});
|
||||
});
|
||||
it('should not throw when variable undefined by default', function() {
|
||||
return expect(engine.parseAndRender('X{{a}}Y')).to.eventually.equal('XY');
|
||||
});
|
||||
it('should throw RenderError when variable not defined', function() {
|
||||
return expect(strictEngine.parseAndRender('{{a}}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function(e) {
|
||||
expect(e).to.have.property('name', 'RenderError');
|
||||
expect(e.message).to.contain('undefined variable: a');
|
||||
});
|
||||
});
|
||||
it('should contain template content in err.message', function() {
|
||||
var html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th'];
|
||||
var message = [
|
||||
'intended render error',
|
||||
' 2| 2nd',
|
||||
' 3| 3rd',
|
||||
'>> 4| X{%throwingTag%} Y',
|
||||
' 5| 5th',
|
||||
' 6| 6th',
|
||||
' 7| 7th'
|
||||
];
|
||||
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.message).to.equal(message.join('\n'));
|
||||
expect(err.name).to.equal('RenderError');
|
||||
});
|
||||
});
|
||||
it('should contain the whole template content in err.input', function() {
|
||||
var html = 'bar\nfoo{%throwingTag%}\nfoo';
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.input).to.equal(html);
|
||||
expect(err.name).to.equal('RenderError');
|
||||
});
|
||||
});
|
||||
it('should contain line number in err.line', function() {
|
||||
var src = '1\n2\n{{1|throwingFilter}}\n4';
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.line).to.equal(3);
|
||||
expect(err.name).to.equal('RenderError');
|
||||
});
|
||||
});
|
||||
it('should contain stack in err.stack', function() {
|
||||
return expect(engine.parseAndRender('{%rejectingTag%}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.stack).to.contain('intended render reject');
|
||||
expect(err.stack).to.contain('at Object.engine.registerTag.render');
|
||||
});
|
||||
});
|
||||
describe('RenderError', function () {
|
||||
beforeEach(function () {
|
||||
engine = require('../..')({
|
||||
root: '/'
|
||||
})
|
||||
engine.registerTag('throwingTag', {
|
||||
render: function () {
|
||||
throw new Error('intended render error')
|
||||
}
|
||||
})
|
||||
engine.registerTag('rejectingTag', {
|
||||
render: function () {
|
||||
return Promise.reject(new Error('intended render reject'))
|
||||
}
|
||||
})
|
||||
engine.registerFilter('throwingFilter', () => {
|
||||
throw new Error('throwed by filter')
|
||||
})
|
||||
})
|
||||
it('should throw RenderError when tag throws', function () {
|
||||
var src = '{%throwingTag%}'
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('RenderError')
|
||||
expect(err.message).to.contain('intended render error')
|
||||
})
|
||||
})
|
||||
it('should throw RenderError when tag rejects', function () {
|
||||
var src = '{%rejectingTag%}'
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('RenderError')
|
||||
expect(err.message).to.contain('intended render reject')
|
||||
})
|
||||
})
|
||||
it('should throw RenderError when filter throws', function () {
|
||||
var src = '{{1|throwingFilter}}'
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('RenderError')
|
||||
expect(err.message).to.contain('throwed by filter')
|
||||
})
|
||||
})
|
||||
it('should not throw when variable undefined by default', function () {
|
||||
return expect(engine.parseAndRender('X{{a}}Y')).to.eventually.equal('XY')
|
||||
})
|
||||
it('should throw RenderError when variable not defined', function () {
|
||||
return expect(strictEngine.parseAndRender('{{a}}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (e) {
|
||||
expect(e).to.have.property('name', 'RenderError')
|
||||
expect(e.message).to.contain('undefined variable: a')
|
||||
})
|
||||
})
|
||||
it('should contain template context in err.stack', function () {
|
||||
var html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
|
||||
var message = [
|
||||
' 2| 2nd',
|
||||
' 3| 3rd',
|
||||
'>> 4| X{%throwingTag%} Y',
|
||||
' 5| 5th',
|
||||
' 6| 6th',
|
||||
' 7| 7th',
|
||||
'RenderError'
|
||||
]
|
||||
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.equal('intended render error, line:4')
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
})
|
||||
it('should contain original error info for {% layout %}', function () {
|
||||
mock({
|
||||
'/throwing-tag.html': [
|
||||
'1st',
|
||||
'2nd',
|
||||
'3rd',
|
||||
'X{%throwingTag%} Y',
|
||||
'5th',
|
||||
'{%block%}{%endblock%}',
|
||||
'7th'
|
||||
].join('\n')
|
||||
})
|
||||
var html = '{%layout "throwing-tag.html"%}'
|
||||
var message = [
|
||||
' 2| 2nd',
|
||||
' 3| 3rd',
|
||||
'>> 4| X{%throwingTag%} Y',
|
||||
' 5| 5th',
|
||||
' 6| {%block%}{%endblock%}',
|
||||
' 7| 7th',
|
||||
'RenderError'
|
||||
]
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
console.log(err.message)
|
||||
console.log(err.stack)
|
||||
expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4`)
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
})
|
||||
it('should contain original error info for {% include %}', function () {
|
||||
var origin = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
|
||||
mock({
|
||||
'/throwing-tag.html': origin.join('\n')
|
||||
})
|
||||
var html = '{%include "throwing-tag.html"%}'
|
||||
var message = [
|
||||
' 2| 2nd',
|
||||
' 3| 3rd',
|
||||
'>> 4| X{%throwingTag%} Y',
|
||||
' 5| 5th',
|
||||
' 6| 6th',
|
||||
' 7| 7th',
|
||||
'RenderError'
|
||||
]
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4`)
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
})
|
||||
it('should contain the whole template content in err.input', function () {
|
||||
var html = 'bar\nfoo{%throwingTag%}\nfoo'
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.input).to.equal(html)
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
})
|
||||
it('should contain line number in err.line', function () {
|
||||
var src = '1\n2\n{{1|throwingFilter}}\n4'
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.line).to.equal(3)
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
})
|
||||
it('should contain stack in err.stack', function () {
|
||||
return expect(engine.parseAndRender('{%rejectingTag%}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.contain('intended render reject')
|
||||
expect(err.stack).to.match(/at .*:\d+:\d+/)
|
||||
})
|
||||
})
|
||||
|
||||
it('should contain file path in err.file', function() {
|
||||
var html = '<html>\n<head>\n\n{% throwingTag %}\n\n';
|
||||
mock({
|
||||
"/foo.html": html
|
||||
});
|
||||
return expect(engine.renderFile('/foo.html')).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
mock.restore();
|
||||
expect(err.name).to.equal('RenderError');
|
||||
expect(err.file).to.equal('/foo.html');
|
||||
});
|
||||
});
|
||||
});
|
||||
it('should contain file path in err.file', function () {
|
||||
var html = '<html>\n<head>\n\n{% throwingTag %}\n\n'
|
||||
mock({
|
||||
'/foo.html': html
|
||||
})
|
||||
return expect(engine.renderFile('/foo.html')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
mock.restore()
|
||||
expect(err.name).to.equal('RenderError')
|
||||
expect(err.file).to.equal(path.resolve('/foo.html'))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('ParseError', function() {
|
||||
beforeEach(function() {
|
||||
engine = require('../..')();
|
||||
engine.registerTag('throwsOnParse', {
|
||||
parse: function() {
|
||||
throw new Error('intended parse error');
|
||||
}
|
||||
});
|
||||
});
|
||||
it('should throw RenderError when filter not defined', function() {
|
||||
return expect(strictEngine.parseAndRender('{{1 | a}}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function(e) {
|
||||
expect(e).to.have.property('name', 'ParseError');
|
||||
expect(e.message).to.contain('undefined filter: a');
|
||||
});
|
||||
});
|
||||
it('should throw ParseError when tag not closed', function() {
|
||||
return expect(engine.parseAndRender('{% if %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.name).to.equal('ParseError');
|
||||
expect(err.message).to.contain('tag {% if %} not closed');
|
||||
});
|
||||
});
|
||||
it('should throw ParseError when tag parse throws', function() {
|
||||
var src = '{%throwsOnParse%}';
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.name).to.equal('ParseError');
|
||||
expect(err.message).to.contain('intended parse error');
|
||||
});
|
||||
});
|
||||
it('should throw ParseError when tag not found', function() {
|
||||
var src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3';
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.name).to.equal('ParseError');
|
||||
expect(err.message).to.contain('tag -a not found');
|
||||
});
|
||||
});
|
||||
describe('ParseError', function () {
|
||||
beforeEach(function () {
|
||||
engine = require('../..')()
|
||||
engine.registerTag('throwsOnParse', {
|
||||
parse: function () {
|
||||
throw new Error('intended parse error')
|
||||
}
|
||||
})
|
||||
})
|
||||
it('should throw RenderError when filter not defined', function () {
|
||||
return expect(strictEngine.parseAndRender('{{1 | a}}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (e) {
|
||||
expect(e).to.have.property('name', 'ParseError')
|
||||
expect(e.message).to.contain('undefined filter: a')
|
||||
})
|
||||
})
|
||||
it('should throw ParseError when tag not closed', function () {
|
||||
return expect(engine.parseAndRender('{% if %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.message).to.contain('tag {% if %} not closed')
|
||||
})
|
||||
})
|
||||
it('should throw ParseError when tag parse throws', function () {
|
||||
var src = '{%throwsOnParse%}'
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.message).to.contain('intended parse error')
|
||||
})
|
||||
})
|
||||
it('should throw ParseError when tag not found', function () {
|
||||
var src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3'
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.message).to.contain('tag -a not found')
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw ParseError when tag not exist', function() {
|
||||
return expect(engine.parseAndRender('{% a %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.name).to.equal('ParseError');
|
||||
expect(err.message).to.contain('tag a not found');
|
||||
});
|
||||
});
|
||||
it('should throw ParseError when tag not exist', function () {
|
||||
return expect(engine.parseAndRender('{% a %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.message).to.contain('tag a not found')
|
||||
})
|
||||
})
|
||||
|
||||
it('should contain template content in err.message', function() {
|
||||
var html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th'];
|
||||
var message = [
|
||||
'tag a not found',
|
||||
' 2| 2nd',
|
||||
' 3| 3rd',
|
||||
'>> 4| X{% a %} {% enda %} Y',
|
||||
' 5| 5th',
|
||||
' 6| 6th',
|
||||
' 7| 7th'
|
||||
];
|
||||
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.message).to.equal(message.join('\n'));
|
||||
expect(err.name).to.equal('ParseError');
|
||||
});
|
||||
});
|
||||
it('should contain template context in err.stack', function () {
|
||||
var html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th']
|
||||
var message = [
|
||||
' 2| 2nd',
|
||||
' 3| 3rd',
|
||||
'>> 4| X{% a %} {% enda %} Y',
|
||||
' 5| 5th',
|
||||
' 6| 6th',
|
||||
' 7| 7th',
|
||||
'ParseError: tag a not found'
|
||||
]
|
||||
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.equal('tag a not found, line:4')
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('ParseError')
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle err.message when context not enough', function() {
|
||||
var html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th'];
|
||||
var message = [
|
||||
'tag a not found',
|
||||
' 1| 1st',
|
||||
'>> 2| X{% a %} {% enda %} Y',
|
||||
' 3| 3rd',
|
||||
' 4| 4th'
|
||||
];
|
||||
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.message).to.equal(message.join('\n'));
|
||||
});
|
||||
});
|
||||
it('should handle err.message when context not enough', function () {
|
||||
var html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th']
|
||||
var message = [
|
||||
' 1| 1st',
|
||||
'>> 2| X{% a %} {% enda %} Y',
|
||||
' 3| 3rd',
|
||||
' 4| 4th',
|
||||
'ParseError: tag a not found'
|
||||
]
|
||||
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.equal('tag a not found, line:2')
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
})
|
||||
})
|
||||
|
||||
it('should contain the whole template content in err.input', function() {
|
||||
var html = 'bar\nfoo{% a %}\nfoo';
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.input).to.equal(html);
|
||||
});
|
||||
});
|
||||
it('should contain line number in err.line', function () {
|
||||
var html = '<html>\n<head>\n\n{% raw %}\n\n'
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.line).to.equal(4)
|
||||
})
|
||||
})
|
||||
|
||||
it('should contain line number in err.line', function() {
|
||||
var html = '<html>\n<head>\n\n{% raw %}\n\n';
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.line).to.equal(4);
|
||||
});
|
||||
});
|
||||
it('should contain stack in err.stack', function () {
|
||||
return expect(engine.parseAndRender('{% -a %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.stack).to.contain('ParseError: tag -a not found')
|
||||
expect(err.stack).to.match(/at .*:\d+:\d+\)/)
|
||||
})
|
||||
})
|
||||
|
||||
it('should contain stack in err.stack', function() {
|
||||
return expect(engine.parseAndRender('{% -a %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
expect(err.stack).to.contain('AssertionError: tag -a not found');
|
||||
expect(err.stack).to.contain('at Object._tagInstance.parse');
|
||||
});
|
||||
});
|
||||
|
||||
it('should contain file path in err.file', function() {
|
||||
var html = '<html>\n<head>\n\n{% raw %}\n\n';
|
||||
mock({
|
||||
"/foo.html": html
|
||||
});
|
||||
return expect(engine.renderFile('/foo.html')).to.eventually
|
||||
.be.rejected
|
||||
.then(function(err) {
|
||||
mock.restore();
|
||||
expect(err.name).to.equal('ParseError');
|
||||
expect(err.file).to.equal('/foo.html');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
it('should contain file path in err.file', function () {
|
||||
var html = '<html>\n<head>\n\n{% raw %}\n\n'
|
||||
mock({
|
||||
'/foo.html': html
|
||||
})
|
||||
return expect(engine.renderFile('/foo.html')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
mock.restore()
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.file).to.equal(path.resolve('/foo.html'))
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+92
-90
@@ -1,92 +1,94 @@
|
||||
const chai = require("chai");
|
||||
const sinon = require('sinon');
|
||||
const expect = chai.expect;
|
||||
chai.use(require("chai-as-promised"));
|
||||
chai.use(require("sinon-chai"));
|
||||
const chai = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
chai.use(require('sinon-chai'))
|
||||
|
||||
var P = require('../../src/util/promise.js');
|
||||
var P = require('../../src/util/promise.js')
|
||||
|
||||
describe('util/promise', function() {
|
||||
describe('.anySeries()', function() {
|
||||
it('should resolve in series', function() {
|
||||
var spy1 = sinon.spy(),
|
||||
spy2 = sinon.spy();
|
||||
return P
|
||||
.anySeries(
|
||||
['first', 'second'],
|
||||
(item, idx) => new Promise(function(resolve, reject) {
|
||||
if (idx === 0) {
|
||||
setTimeout(function() {
|
||||
spy1();
|
||||
reject(new Error('first cb'));
|
||||
}, 10);
|
||||
} else {
|
||||
spy2();
|
||||
resolve('foo');
|
||||
}
|
||||
}))
|
||||
.then(() => expect(spy2).to.have.been.calledAfter(spy1));
|
||||
});
|
||||
it('should reject when all rejected', function() {
|
||||
var p = P.anySeries(['first', 'second', 'third'],
|
||||
item => Promise.reject(new Error(item)));
|
||||
return expect(p).to.be.rejectedWith("third");
|
||||
});
|
||||
it('should resolve the value that first callback resolved', () => {
|
||||
var p = P.anySeries(['first', 'second'],
|
||||
item => Promise.resolve(item));
|
||||
return expect(p).to.eventually.equal('first');
|
||||
});
|
||||
it('should not call rest of callbacks once resolved', () => {
|
||||
var spy = sinon.spy();
|
||||
return P.anySeries(['first', 'second'], (item, idx) => {
|
||||
if (idx > 0) {
|
||||
spy();
|
||||
}
|
||||
return Promise.resolve(item);
|
||||
})
|
||||
.then(() => expect(spy).to.not.have.been.called);
|
||||
});
|
||||
});
|
||||
describe('.mapSeries()', function() {
|
||||
it('should resolve when all resolved', function() {
|
||||
var p = P.mapSeries(['first', 'second', 'third'],
|
||||
item => Promise.resolve(item));
|
||||
return expect(p).to.eventually.deep.equal(['first', 'second', "third"]);
|
||||
});
|
||||
it('should reject with the error that first callback rejected', () => {
|
||||
var p = P.mapSeries(['first', 'second'],
|
||||
item => Promise.reject(item));
|
||||
return expect(p).to.rejectedWith('first');
|
||||
});
|
||||
it('should resolve in series', function() {
|
||||
var spy1 = sinon.spy(),
|
||||
spy2 = sinon.spy();
|
||||
return P
|
||||
.mapSeries(
|
||||
['first', 'second'],
|
||||
(item, idx) => new Promise(function(resolve, reject) {
|
||||
if (idx === 0) {
|
||||
setTimeout(function() {
|
||||
spy1();
|
||||
resolve('first cb');
|
||||
}, 10);
|
||||
} else {
|
||||
spy2();
|
||||
resolve('foo');
|
||||
}
|
||||
}))
|
||||
.then(() => expect(spy2).to.have.been.calledAfter(spy1));
|
||||
});
|
||||
it('should not call rest of callbacks once rejected', () => {
|
||||
var spy = sinon.spy();
|
||||
return P.mapSeries(['first', 'second'], (item, idx) => {
|
||||
if (idx > 0) {
|
||||
spy();
|
||||
}
|
||||
return Promise.reject(new Error(item));
|
||||
})
|
||||
.catch(() => expect(spy).to.not.have.been.called);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('util/promise', function () {
|
||||
describe('.anySeries()', function () {
|
||||
it('should resolve in series', function () {
|
||||
var spy1 = sinon.spy()
|
||||
var spy2 = sinon.spy()
|
||||
return P
|
||||
.anySeries(
|
||||
['first', 'second'],
|
||||
(item, idx) => new Promise(function (resolve, reject) {
|
||||
if (idx === 0) {
|
||||
setTimeout(function () {
|
||||
spy1()
|
||||
reject(new Error('first cb'))
|
||||
}, 10)
|
||||
} else {
|
||||
spy2()
|
||||
resolve('foo')
|
||||
}
|
||||
}))
|
||||
.then(() => expect(spy2).to.have.been.calledAfter(spy1))
|
||||
})
|
||||
it('should reject when all rejected', function () {
|
||||
var p = P.anySeries(['first', 'second', 'third'],
|
||||
item => Promise.reject(new Error(item)))
|
||||
return expect(p).to.be.rejectedWith('third')
|
||||
})
|
||||
it('should resolve the value that first callback resolved', () => {
|
||||
var p = P.anySeries(['first', 'second'],
|
||||
item => Promise.resolve(item))
|
||||
return expect(p).to.eventually.equal('first')
|
||||
})
|
||||
it('should not call rest of callbacks once resolved', () => {
|
||||
var spy = sinon.spy()
|
||||
return P
|
||||
.anySeries(['first', 'second'], (item, idx) => {
|
||||
if (idx > 0) {
|
||||
spy()
|
||||
}
|
||||
return Promise.resolve(item)
|
||||
})
|
||||
.then(() => expect(spy).to.not.have.been.called)
|
||||
})
|
||||
})
|
||||
describe('.mapSeries()', function () {
|
||||
it('should resolve when all resolved', function () {
|
||||
var p = P.mapSeries(['first', 'second', 'third'],
|
||||
item => Promise.resolve(item))
|
||||
return expect(p).to.eventually.deep.equal(['first', 'second', 'third'])
|
||||
})
|
||||
it('should reject with the error that first callback rejected', () => {
|
||||
var p = P.mapSeries(['first', 'second'],
|
||||
item => Promise.reject(item))
|
||||
return expect(p).to.rejectedWith('first')
|
||||
})
|
||||
it('should resolve in series', function () {
|
||||
var spy1 = sinon.spy()
|
||||
var spy2 = sinon.spy()
|
||||
return P
|
||||
.mapSeries(
|
||||
['first', 'second'],
|
||||
(item, idx) => new Promise(function (resolve, reject) {
|
||||
if (idx === 0) {
|
||||
setTimeout(function () {
|
||||
spy1()
|
||||
resolve('first cb')
|
||||
}, 10)
|
||||
} else {
|
||||
spy2()
|
||||
resolve('foo')
|
||||
}
|
||||
}))
|
||||
.then(() => expect(spy2).to.have.been.calledAfter(spy1))
|
||||
})
|
||||
it('should not call rest of callbacks once rejected', () => {
|
||||
var spy = sinon.spy()
|
||||
return P
|
||||
.mapSeries(['first', 'second'], (item, idx) => {
|
||||
if (idx > 0) {
|
||||
spy()
|
||||
}
|
||||
return Promise.reject(new Error(item))
|
||||
})
|
||||
.catch(() => expect(spy).to.not.have.been.called)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+136
-110
@@ -1,120 +1,146 @@
|
||||
const chai = require("chai");
|
||||
const expect = chai.expect;
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
|
||||
var t = require('../../src/util/strftime.js');
|
||||
var t = require('../../src/util/strftime.js')
|
||||
|
||||
describe('util/strftime', function() {
|
||||
var now;
|
||||
before(function() {
|
||||
mockUTC();
|
||||
now = new Date('2016-01-04T13:15:23');
|
||||
then = new Date('2016-03-06T03:05:03');
|
||||
});
|
||||
after(function() {
|
||||
restoreUTC();
|
||||
});
|
||||
describe('util/strftime', function () {
|
||||
var now
|
||||
var then
|
||||
before(function () {
|
||||
mockUTC()
|
||||
now = new Date('2016-01-04T13:15:23.000Z')
|
||||
then = new Date('2016-03-06T03:05:03.000Z')
|
||||
})
|
||||
after(function () {
|
||||
restoreUTC()
|
||||
})
|
||||
|
||||
it('should format UTC datetime', function() {
|
||||
expect(t(now, '%Y-%m-%dT%H:%M:%S')).to.equal('2016-01-04T13:15:23');
|
||||
});
|
||||
it('should format %A as Monday', function() {
|
||||
expect(t(now, '%A')).to.equal('Monday');
|
||||
});
|
||||
it('should format %B as month name', function() {
|
||||
expect(t(now, '%B')).to.equal('January');
|
||||
});
|
||||
it('should format %C as century', function() {
|
||||
expect(t(now, '%C')).to.equal('20');
|
||||
});
|
||||
it('should format %c as local string', function() {
|
||||
expect(t(now, '%c')).to.equal(now.toLocaleString());
|
||||
});
|
||||
it('should format %e as space padded date', function() {
|
||||
expect(t(now, '%e')).to.equal(' 4');
|
||||
});
|
||||
it('should format %I as 0 padded hour12', function() {
|
||||
expect(t(now, '%I')).to.equal('01');
|
||||
});
|
||||
it('should format %j as day of year', function() {
|
||||
expect(t(then, '%j')).to.equal('066');
|
||||
});
|
||||
it('should format %k as space padded hour', function() {
|
||||
expect(t(then, '%k')).to.equal(' 3');
|
||||
});
|
||||
it('should format %l as space padded hour12', function() {
|
||||
expect(t(now, '%l')).to.equal(' 1');
|
||||
});
|
||||
it('should format %L as 0 padded millisecond', function() {
|
||||
expect(t(then, '%L')).to.equal('000');
|
||||
});
|
||||
it('should format %p as upper cased am/pm', function() {
|
||||
expect(t(now, '%p')).to.equal('PM');
|
||||
expect(t(then, '%p')).to.equal('AM');
|
||||
});
|
||||
it('should format %P as lower cased am/pm', function() {
|
||||
expect(t(now, '%P')).to.equal('pm');
|
||||
expect(t(then, '%P')).to.equal('am');
|
||||
});
|
||||
it('should format %q as date suffix', function(){
|
||||
var st = new Date('2016-03-01T03:05:03');
|
||||
var nd = new Date('2016-03-02T03:05:03');
|
||||
var rd = new Date('2016-03-03T03:05:03');
|
||||
expect(t(st, '%q')).to.equal('st');
|
||||
expect(t(nd, '%q')).to.equal('nd');
|
||||
expect(t(rd, '%q')).to.equal('rd');
|
||||
expect(t(now, '%q')).to.equal('th');
|
||||
});
|
||||
it('should format %s as UNIX seconds', function(){
|
||||
expect(t(now, '%s')).to.be.match(/\d+/);
|
||||
});
|
||||
it('should format %u as day of week(1-7)', function(){
|
||||
expect(t(now, '%u')).to.be.equal('1');
|
||||
expect(t(then, '%u')).to.be.equal('7');
|
||||
});
|
||||
it('should format %U as week of year, starts with 0', function() {
|
||||
expect(t(now, '%U')).to.equal('01');
|
||||
});
|
||||
it('should format %w as day of month(0-7)', function(){
|
||||
expect(t(now, '%w')).to.be.equal('1');
|
||||
expect(t(then, '%w')).to.be.equal('0');
|
||||
});
|
||||
it('should format %W as week of year, starts with 1', function(){
|
||||
expect(t(now, '%W')).to.be.equal('01');
|
||||
});
|
||||
it('should format %x as local date string', function() {
|
||||
expect(t(now, '%x')).to.equal(now.toLocaleDateString());
|
||||
});
|
||||
it('should format %X as local time string', function() {
|
||||
expect(t(now, '%X')).to.equal(now.toLocaleTimeString());
|
||||
});
|
||||
it('should format %y as 2-digit year', function() {
|
||||
expect(t(now, '%y')).to.equal('16');
|
||||
});
|
||||
it('should format %z as time zone', function() {
|
||||
expect(t(now, '%z')).to.equal('+0800');
|
||||
});
|
||||
it('should escape %% as %', function() {
|
||||
expect(t(now, '%%')).to.equal('%');
|
||||
});
|
||||
});
|
||||
it('should format UTC datetime', function () {
|
||||
expect(t(now, '%Y-%m-%dT%H:%M:%S')).to.equal('2016-01-04T13:15:23')
|
||||
})
|
||||
it('should format %A as Monday', function () {
|
||||
expect(t(now, '%A')).to.equal('Monday')
|
||||
})
|
||||
it('should format %B as month name', function () {
|
||||
expect(t(now, '%B')).to.equal('January')
|
||||
})
|
||||
it('should format %C as century', function () {
|
||||
expect(t(now, '%C')).to.equal('20')
|
||||
})
|
||||
it('should format %c as local string', function () {
|
||||
expect(t(now, '%c')).to.equal(now.toLocaleString())
|
||||
})
|
||||
it('should format %e as space padded date', function () {
|
||||
expect(t(now, '%e')).to.equal(' 4')
|
||||
})
|
||||
it('should format %I as 0 padded hour12', function () {
|
||||
expect(t(now, '%I')).to.equal('01')
|
||||
})
|
||||
it('should format %I as 12 for 00:00', function () {
|
||||
var date = new Date('2016-01-01T00:00:00.000Z')
|
||||
expect(t(date, '%I')).to.equal('12')
|
||||
})
|
||||
describe('%j', function () {
|
||||
it('should format %j as day of year', function () {
|
||||
expect(t(then, '%j')).to.equal('066')
|
||||
})
|
||||
it('should take count of leap years', function () {
|
||||
var date = new Date('2001-03-01')
|
||||
expect(t(date, '%j')).to.equal('060')
|
||||
})
|
||||
it('should take count of leap years', function () {
|
||||
var date = new Date('2000-03-01')
|
||||
expect(t(date, '%j')).to.equal('061')
|
||||
})
|
||||
})
|
||||
it('should format %k as space padded hour', function () {
|
||||
expect(t(then, '%k')).to.equal(' 3')
|
||||
})
|
||||
it('should format %l as space padded hour12', function () {
|
||||
expect(t(now, '%l')).to.equal(' 1')
|
||||
})
|
||||
it('should format %l as 12 for 00:00', function () {
|
||||
var date = new Date('2016-01-01T00:00:00.000Z')
|
||||
expect(t(date, '%l')).to.equal('12')
|
||||
})
|
||||
it('should format %L as 0 padded millisecond', function () {
|
||||
expect(t(then, '%L')).to.equal('000')
|
||||
})
|
||||
it('should format %p as upper cased am/pm', function () {
|
||||
expect(t(now, '%p')).to.equal('PM')
|
||||
expect(t(then, '%p')).to.equal('AM')
|
||||
})
|
||||
it('should format %P as lower cased am/pm', function () {
|
||||
expect(t(now, '%P')).to.equal('pm')
|
||||
expect(t(then, '%P')).to.equal('am')
|
||||
})
|
||||
it('should format %q as date suffix', function () {
|
||||
var st = new Date('2016-03-01T03:05:03.000Z')
|
||||
var nd = new Date('2016-03-02T03:05:03.000Z')
|
||||
var rd = new Date('2016-03-03T03:05:03.000Z')
|
||||
expect(t(st, '%q')).to.equal('st')
|
||||
expect(t(nd, '%q')).to.equal('nd')
|
||||
expect(t(rd, '%q')).to.equal('rd')
|
||||
expect(t(now, '%q')).to.equal('th')
|
||||
})
|
||||
it('should format %s as UNIX seconds', function () {
|
||||
expect(t(now, '%s')).to.be.match(/\d+/)
|
||||
})
|
||||
it('should format %u as day of week(1-7)', function () {
|
||||
expect(t(now, '%u')).to.be.equal('1')
|
||||
expect(t(then, '%u')).to.be.equal('7')
|
||||
})
|
||||
it('should format %U as week of year, starts with 0', function () {
|
||||
expect(t(now, '%U')).to.equal('01')
|
||||
})
|
||||
it('should format %w as day of month(0-7)', function () {
|
||||
expect(t(now, '%w')).to.be.equal('1')
|
||||
expect(t(then, '%w')).to.be.equal('0')
|
||||
})
|
||||
it('should format %W as week of year, starts with 1', function () {
|
||||
expect(t(now, '%W')).to.be.equal('01')
|
||||
})
|
||||
it('should format %x as local date string', function () {
|
||||
expect(t(now, '%x')).to.equal(now.toLocaleDateString())
|
||||
})
|
||||
it('should format %X as local time string', function () {
|
||||
expect(t(now, '%X')).to.equal(now.toLocaleTimeString())
|
||||
})
|
||||
it('should format %y as 2-digit year', function () {
|
||||
expect(t(now, '%y')).to.equal('16')
|
||||
})
|
||||
it('should format %z as time zone', function () {
|
||||
expect(t(now, '%z')).to.equal('+0800')
|
||||
})
|
||||
it('should format %z as negative time zone', function () {
|
||||
var date = new Date('2016-01-04T13:15:23.000Z')
|
||||
date.getTimezoneOffset = () => 480
|
||||
expect(t(date, '%z')).to.equal('-0800')
|
||||
})
|
||||
it('should escape %% as %', function () {
|
||||
expect(t(now, '%%')).to.equal('%')
|
||||
})
|
||||
it('should retain un-recognized formaters', function () {
|
||||
expect(t(now, '%o')).to.equal('%o')
|
||||
})
|
||||
})
|
||||
|
||||
function mockUTC () {
|
||||
var p = Date.prototype
|
||||
|
||||
function mockUTC() {
|
||||
var p = Date.prototype;
|
||||
p._getHours = p.getHours
|
||||
p.getHours = p.getUTCHours
|
||||
|
||||
p._getHours = p.getHours;
|
||||
p.getHours = p.getUTCHours;
|
||||
p._getDays = p.getDays
|
||||
p.getDays = p.getUTCDays
|
||||
|
||||
p._getDays = p.getDays;
|
||||
p.getDays = p.getUTCDays;
|
||||
|
||||
p._getTimezoneOffset = p._getTimezoneOffset;
|
||||
p.getTimezoneOffset = () => -480;
|
||||
p._getTimezoneOffset = p._getTimezoneOffset
|
||||
p.getTimezoneOffset = () => -480
|
||||
}
|
||||
|
||||
function restoreUTC() {
|
||||
var p = Date.prototype;
|
||||
p.getHours = p._getHours;
|
||||
p.getDays = p._getDays;
|
||||
p.getTimezoneOffset = p._getTimezoneOffset;
|
||||
function restoreUTC () {
|
||||
var p = Date.prototype
|
||||
p.getHours = p._getHours
|
||||
p.getDays = p._getDays
|
||||
p.getTimezoneOffset = p._getTimezoneOffset
|
||||
}
|
||||
|
||||
+116
-126
@@ -1,128 +1,118 @@
|
||||
const chai = require("chai");
|
||||
const sinon = require('sinon');
|
||||
const expect = chai.expect;
|
||||
const Errors = require('../../src/util/error.js');
|
||||
chai.use(require("sinon-chai"));
|
||||
const chai = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const expect = chai.expect
|
||||
const Errors = require('../../src/util/error.js')
|
||||
chai.use(require('sinon-chai'))
|
||||
|
||||
var _ = require('../../src/util/underscore.js');
|
||||
var _ = require('../../src/util/underscore.js')
|
||||
|
||||
describe('util/underscore', function() {
|
||||
describe('.isError()', function() {
|
||||
it('should return true for new Error', function() {
|
||||
expect(_.isError(new Error())).to.be.true;
|
||||
});
|
||||
it('should return true for RenderError', function() {
|
||||
var tpl = {
|
||||
token: {
|
||||
input: 'xx'
|
||||
}
|
||||
};
|
||||
expect(_.isError(new Errors.RenderError(new Error(), tpl))).to.be.true;
|
||||
});
|
||||
it('should return true for RenderBreakError', function() {
|
||||
expect(_.isError(new Errors.RenderBreakError())).to.be.true;
|
||||
});
|
||||
});
|
||||
describe('.isString()', function() {
|
||||
it('should return true for literal string', function() {
|
||||
expect(_.isString('foo')).to.be.true;
|
||||
});
|
||||
it('should return true String instance', function() {
|
||||
expect(_.isString(String('foo'))).to.be.true;
|
||||
});
|
||||
it('should return false for 123 ', function() {
|
||||
expect(_.isString(123)).to.be.false;
|
||||
});
|
||||
});
|
||||
describe('.forOwn()', function() {
|
||||
it('should iterate all properties', function() {
|
||||
var spy = sinon.spy();
|
||||
var obj = {
|
||||
foo: "bar"
|
||||
};
|
||||
_.forOwn(obj, spy);
|
||||
expect(spy).to.have.been.calledWith('bar', 'foo', obj);
|
||||
});
|
||||
it('should not iterate over properties on prototype', function() {
|
||||
var spy = sinon.spy();
|
||||
var obj = Object.create({
|
||||
bar: 'foo'
|
||||
});
|
||||
obj.foo = 'bar';
|
||||
_.forOwn(obj, spy);
|
||||
expect(spy).to.have.been.calledOnce;
|
||||
expect(spy).to.have.been.calledWith('bar', 'foo', obj);
|
||||
});
|
||||
it('should break when returned false', function() {
|
||||
var spy = sinon.stub().returns(false);
|
||||
_.forOwn({
|
||||
'foo': 'foo',
|
||||
'bar': 'foo'
|
||||
}, spy);
|
||||
expect(spy).to.have.been.calledOnce;
|
||||
});
|
||||
});
|
||||
describe('.isArray()', function() {
|
||||
it('should return true for []', function() {
|
||||
expect(_.isArray([])).to.be.true;
|
||||
});
|
||||
it('should return false for "foo"', function() {
|
||||
expect(_.isArray("foo")).to.be.false;
|
||||
});
|
||||
});
|
||||
describe('.echo()', function() {
|
||||
it('should be transparent', function() {
|
||||
expect(_.echo('foo')('bar')).to.equal('bar');
|
||||
});
|
||||
it('should log the arguments', function() {
|
||||
var log = sinon.spy(console, 'log');
|
||||
_.echo('foo')('bar');
|
||||
expect(log).to.have.been.calledWith('[foo]', 'bar');
|
||||
});
|
||||
});
|
||||
describe('.assign()', function() {
|
||||
it('should handle null dst', function() {
|
||||
expect(_.assign(null, {
|
||||
foo: 'bar'
|
||||
})).to.deep.equal({
|
||||
foo: 'bar'
|
||||
});
|
||||
});
|
||||
it('should assign 2 objects', function() {
|
||||
var src = {
|
||||
foo: 'foo',
|
||||
bar: 'bar'
|
||||
};
|
||||
var dst = {
|
||||
foo: 'bar',
|
||||
kaa: 'kaa'
|
||||
};
|
||||
expect(_.assign(dst, src)).to.deep.equal({
|
||||
foo: 'foo',
|
||||
bar: 'bar',
|
||||
kaa: 'kaa'
|
||||
});
|
||||
});
|
||||
it('should assign 3 objects', function() {
|
||||
expect(_.assign({
|
||||
foo: 'foo'
|
||||
}, {
|
||||
bar: 'bar'
|
||||
}, {
|
||||
car: 'car'
|
||||
})).to.deep.equal({
|
||||
foo: 'foo',
|
||||
bar: 'bar',
|
||||
car: 'car'
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('.uniq()', function() {
|
||||
it('should handle empty array', function() {
|
||||
expect(_.uniq([])).to.deep.equal([]);
|
||||
});
|
||||
it('should do uniq', function() {
|
||||
expect(_.uniq([1, 'a', 'a', 1])).to.deep.equal([1, 'a']);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('util/underscore', function () {
|
||||
describe('.isError()', function () {
|
||||
it('should return true for new Error', function () {
|
||||
expect(_.isError(new Error())).to.be.true
|
||||
})
|
||||
it('should return true for RenderError', function () {
|
||||
var tpl = {
|
||||
token: {
|
||||
input: 'xx'
|
||||
}
|
||||
}
|
||||
expect(_.isError(new Errors.RenderError(new Error(), tpl))).to.be.true
|
||||
})
|
||||
it('should return true for RenderBreakError', function () {
|
||||
expect(_.isError(new Errors.RenderBreakError())).to.be.true
|
||||
})
|
||||
})
|
||||
describe('.isString()', function () {
|
||||
it('should return true for literal string', function () {
|
||||
expect(_.isString('foo')).to.be.true
|
||||
})
|
||||
it('should return true String instance', function () {
|
||||
expect(_.isString(String('foo'))).to.be.true
|
||||
})
|
||||
it('should return false for 123 ', function () {
|
||||
expect(_.isString(123)).to.be.false
|
||||
})
|
||||
})
|
||||
describe('.forOwn()', function () {
|
||||
it('should iterate all properties', function () {
|
||||
var spy = sinon.spy()
|
||||
var obj = {
|
||||
foo: 'bar'
|
||||
}
|
||||
_.forOwn(obj, spy)
|
||||
expect(spy).to.have.been.calledWith('bar', 'foo', obj)
|
||||
})
|
||||
it('should not iterate over properties on prototype', function () {
|
||||
var spy = sinon.spy()
|
||||
var obj = Object.create({
|
||||
bar: 'foo'
|
||||
})
|
||||
obj.foo = 'bar'
|
||||
_.forOwn(obj, spy)
|
||||
expect(spy).to.have.been.calledOnce
|
||||
expect(spy).to.have.been.calledWith('bar', 'foo', obj)
|
||||
})
|
||||
it('should break when returned false', function () {
|
||||
var spy = sinon.stub().returns(false)
|
||||
_.forOwn({
|
||||
'foo': 'foo',
|
||||
'bar': 'foo'
|
||||
}, spy)
|
||||
expect(spy).to.have.been.calledOnce
|
||||
})
|
||||
})
|
||||
describe('.range()', function () {
|
||||
it('should return a range of integers', function () {
|
||||
expect(_.range(3, 5)).to.deep.equal([3, 4])
|
||||
})
|
||||
it('should treat start as 0 if omitted', function () {
|
||||
expect(_.range(3)).to.deep.equal([0, 1, 2])
|
||||
})
|
||||
})
|
||||
describe('.assign()', function () {
|
||||
it('should handle null dst', function () {
|
||||
expect(_.assign(null, {
|
||||
foo: 'bar'
|
||||
})).to.deep.equal({
|
||||
foo: 'bar'
|
||||
})
|
||||
})
|
||||
it('should assign 2 objects', function () {
|
||||
var src = {
|
||||
foo: 'foo',
|
||||
bar: 'bar'
|
||||
}
|
||||
var dst = {
|
||||
foo: 'bar',
|
||||
kaa: 'kaa'
|
||||
}
|
||||
expect(_.assign(dst, src)).to.deep.equal({
|
||||
foo: 'foo',
|
||||
bar: 'bar',
|
||||
kaa: 'kaa'
|
||||
})
|
||||
})
|
||||
it('should assign 3 objects', function () {
|
||||
expect(_.assign({
|
||||
foo: 'foo'
|
||||
}, {
|
||||
bar: 'bar'
|
||||
}, {
|
||||
car: 'car'
|
||||
})).to.deep.equal({
|
||||
foo: 'foo',
|
||||
bar: 'bar',
|
||||
car: 'car'
|
||||
})
|
||||
})
|
||||
})
|
||||
describe('.uniq()', function () {
|
||||
it('should handle empty array', function () {
|
||||
expect(_.uniq([])).to.deep.equal([])
|
||||
})
|
||||
it('should do uniq', function () {
|
||||
expect(_.uniq([1, 'a', 'a', 1])).to.deep.equal([1, 'a'])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
const url = require('../../src/util/url.js')
|
||||
|
||||
describe('util/url', function () {
|
||||
if (process.version.match(/^v(\d+)/)[1] < 8) {
|
||||
return
|
||||
}
|
||||
const JSDOM = require('jsdom').JSDOM
|
||||
var dom
|
||||
beforeEach(function () {
|
||||
dom = new JSDOM(``, {
|
||||
url: 'https://example.com/foo/bar/',
|
||||
contentType: 'text/html',
|
||||
includeNodeLocations: true
|
||||
})
|
||||
global.document = dom.window.document
|
||||
})
|
||||
afterEach(function () {
|
||||
delete global.document
|
||||
})
|
||||
describe('resolve', function () {
|
||||
describe('root', function () {
|
||||
it('should support width relative path', function () {
|
||||
expect(url.resolve('./views', 'foo'))
|
||||
.to.equal('https://example.com/foo/bar/views/foo')
|
||||
expect(url.resolve('./views/', 'foo'))
|
||||
.to.equal('https://example.com/foo/bar/views/foo')
|
||||
})
|
||||
it('should support width absolute path', function () {
|
||||
expect(url.resolve('/views', 'foo'))
|
||||
.to.equal('https://example.com/views/foo')
|
||||
expect(url.resolve('/views/', 'foo'))
|
||||
.to.equal('https://example.com/views/foo')
|
||||
})
|
||||
it('should support with empty', function () {
|
||||
expect(url.resolve('', 'page.html'))
|
||||
.to.equal('https://example.com/foo/bar/page.html')
|
||||
})
|
||||
it('should support with url', function () {
|
||||
expect(url.resolve('https://example.com/views', 'page.html'))
|
||||
.to.equal('https://example.com/views/page.html')
|
||||
expect(url.resolve('https://example.com/views/', 'page.html'))
|
||||
.to.equal('https://example.com/views/page.html')
|
||||
})
|
||||
it('should get the first value when argument is array', function () {
|
||||
expect(url.resolve(['https://example.com/views', 'https://google.com/views'], 'page.html'))
|
||||
.to.equal('https://example.com/views/page.html')
|
||||
expect(url.resolve(['https://example.com/views/', 'https://google.com/views'], 'page.html'))
|
||||
.to.equal('https://example.com/views/page.html')
|
||||
})
|
||||
})
|
||||
describe('path', function () {
|
||||
it('should support width relative path', function () {
|
||||
expect(url.resolve('./views/', 'page.html'))
|
||||
.to.equal('https://example.com/foo/bar/views/page.html')
|
||||
})
|
||||
it('should support with absolute path', function () {
|
||||
expect(url.resolve('/views/', '/page.html'))
|
||||
.to.equal('https://example.com/page.html')
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
))
|
||||
})
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
const Liquid = require('..')
|
||||
const sinon = require('sinon')
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
|
||||
describe('xhr', () => {
|
||||
if (process.version.match(/^v(\d+)/)[1] < 8) {
|
||||
return
|
||||
}
|
||||
const JSDOM = require('jsdom').JSDOM
|
||||
var server, engine, dom
|
||||
beforeEach(() => {
|
||||
server = sinon.createFakeServer()
|
||||
server.autoRespond = true
|
||||
server.respondWith('GET', 'https://example.com/views/hello.html',
|
||||
[200, {'Content-Type': 'text/plain'}, 'hello {{name}}'])
|
||||
dom = new JSDOM('', {
|
||||
url: 'https://example.com/foo/bar.html',
|
||||
contentType: 'text/html',
|
||||
includeNodeLocations: true
|
||||
})
|
||||
global.XMLHttpRequest = sinon.useFakeXMLHttpRequest()
|
||||
global.document = dom.window.document
|
||||
engine = Liquid({
|
||||
root: 'https://example.com/views/',
|
||||
extname: '.html'
|
||||
})
|
||||
})
|
||||
afterEach(() => {
|
||||
server.restore()
|
||||
delete global.XMLHttpRequest
|
||||
delete global.document
|
||||
})
|
||||
describe('#renderFile()', () => {
|
||||
it('should support without extname', () => {
|
||||
return expect(engine.renderFile('hello', {name: 'alice1'}))
|
||||
.to.eventually.equal('hello alice1')
|
||||
})
|
||||
it('should support with extname', () => {
|
||||
return expect(engine.renderFile('hello.html', {name: 'alice2'}))
|
||||
.to.eventually.equal('hello alice2')
|
||||
})
|
||||
it('should support with absolute path', () => {
|
||||
server.respondWith('GET', 'https://example.com/foo.html',
|
||||
[200, {'Content-Type': 'text/plain'}, 'foo'])
|
||||
return expect(engine.renderFile('/foo.html'))
|
||||
.to.eventually.equal('foo')
|
||||
})
|
||||
it('should support with url', () => {
|
||||
return expect(engine.renderFile('https://example.com/views/hello.html', {name: 'alice4'}))
|
||||
.to.eventually.equal('hello alice4')
|
||||
})
|
||||
it('should support include', () => {
|
||||
server.respondWith('GET', 'https://example.com/views/hello.html',
|
||||
[200, {'Content-Type': 'text/plain'}, "hello {% include 'name.html' %}"])
|
||||
server.respondWith('GET', 'https://example.com/views/name.html',
|
||||
[200, {'Content-Type': 'text/plain'}, '{{name}}'])
|
||||
return expect(engine.renderFile('hello.html', {name: 'alice5'}))
|
||||
.to.eventually.equal('hello alice5')
|
||||
})
|
||||
it('should throw 404', () => {
|
||||
return expect(engine.renderFile('/not/exist.html'))
|
||||
.to.be.rejectedWith('Not Found')
|
||||
})
|
||||
it('should throw error', function (done) {
|
||||
engine.renderFile('hello.html')
|
||||
.catch(function (e) {
|
||||
expect(e.message).to.equal('An error occurred whilst sending the response.')
|
||||
done()
|
||||
})
|
||||
server.requests[0].error()
|
||||
})
|
||||
})
|
||||
describe('root', () => {
|
||||
it('should support with null', () => {
|
||||
engine = Liquid({
|
||||
extname: '.html'
|
||||
})
|
||||
server.respondWith('GET', 'https://example.com/foo/hello.html',
|
||||
[200, {'Content-Type': 'text/plain'}, 'hello {{name}}'])
|
||||
return expect(engine.renderFile('hello.html', {name: 'alice5'}))
|
||||
.to.eventually.equal('hello alice5')
|
||||
})
|
||||
it('should support with empty', () => {
|
||||
engine = Liquid({
|
||||
root: '',
|
||||
extname: '.html'
|
||||
})
|
||||
server.respondWith('GET', 'https://example.com/foo/hello.html',
|
||||
[200, {'Content-Type': 'text/plain'}, 'hello {{name}}'])
|
||||
return expect(engine.renderFile('hello.html', {name: 'alice5'}))
|
||||
.to.eventually.equal('hello alice5')
|
||||
})
|
||||
it('should support with relative path', () => {
|
||||
engine = Liquid({
|
||||
root: './views/',
|
||||
extname: '.html'
|
||||
})
|
||||
server.respondWith('GET', 'https://example.com/foo/views/hello.html',
|
||||
[200, {'Content-Type': 'text/plain'}, 'hello {{name}}'])
|
||||
return expect(engine.renderFile('hello.html', {name: 'alice5'}))
|
||||
.to.eventually.equal('hello alice5')
|
||||
})
|
||||
it('should support with absolute path', () => {
|
||||
engine = Liquid({
|
||||
root: '/views/',
|
||||
extname: '.html'
|
||||
})
|
||||
server.respondWith('GET', 'https://example.com/views/hello.html',
|
||||
[200, {'Content-Type': 'text/plain'}, 'hello {{name}}'])
|
||||
return expect(engine.renderFile('hello.html', {name: 'alice5'}))
|
||||
.to.eventually.equal('hello alice5')
|
||||
})
|
||||
it('should support with url', () => {
|
||||
engine = Liquid({
|
||||
root: 'https://foo.com/bar/',
|
||||
extname: '.html'
|
||||
})
|
||||
server.respondWith('GET', 'https://foo.com/bar/hello.html',
|
||||
[200, {'Content-Type': 'text/plain'}, 'hello {{name}}'])
|
||||
return expect(engine.renderFile('hello.html', {name: 'alice5'}))
|
||||
.to.eventually.equal('hello alice5')
|
||||
})
|
||||
})
|
||||
describe('cache options', () => {
|
||||
it('should be disabled by default', () => {
|
||||
server.respondWith('GET', 'https://example.com/views/foo.html',
|
||||
[200, {'Content-Type': 'text/plain'}, 'foo1'])
|
||||
return engine.renderFile('foo.html')
|
||||
.then((html) => {
|
||||
expect(html).to.equal('foo1')
|
||||
server.respondWith('GET', 'https://example.com/views/foo.html',
|
||||
[200, {'Content-Type': 'text/plain'}, 'foo2'])
|
||||
return engine.renderFile('foo.html')
|
||||
})
|
||||
.then(html => expect(html).to.equal('foo2'))
|
||||
})
|
||||
it('should respect cache=true option', () => {
|
||||
engine = Liquid({
|
||||
root: '/views/',
|
||||
extname: '.html',
|
||||
cache: true
|
||||
})
|
||||
server.respondWith('GET', 'https://example.com/views/foo.html',
|
||||
[200, {'Content-Type': 'text/plain'}, 'foo1'])
|
||||
return engine.renderFile('foo.html')
|
||||
.then((html) => {
|
||||
expect(html).to.equal('foo1')
|
||||
server.respondWith('GET', 'https://example.com/views/foo.html',
|
||||
[200, {'Content-Type': 'text/plain'}, 'foo2'])
|
||||
return engine.renderFile('foo.html')
|
||||
})
|
||||
.then(html => expect(html).to.equal('foo1'))
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user