Compare commits

...
117 Commits
Author SHA1 Message Date
Jun Yang d504c8107e 6.0.1 2018-10-06 12:20:13 +08:00
Jun Yang c0181aec31 remove dependency from 'util' 2018-10-01 23:08:39 +08:00
Jun Yang 22a7a85d50 test case for Regexp rendering 2018-10-01 23:00:49 +08:00
Jun Yang 044be8253d fixes #91 2018-10-01 22:51:40 +08:00
Jun Yang 8a629980d9 refactor: move fs util into template.js 2018-10-01 22:06:03 +08:00
harttle 5412c5a39f fixes #88 2018-09-29 16:45:11 +08:00
harttle b7445f26d6 6.0.0 2018-08-28 00:37:00 +08:00
harttle 3213c6d23a fix: ci 2018-08-28 00:27:44 +08:00
harttle 829afc24a7 fix: ci 2018-08-28 00:17:26 +08:00
harttle 0049a56864 fix: ci 2018-08-28 00:05:50 +08:00
harttle f8e0587542 fix: ci 2018-08-27 23:54:43 +08:00
harttle c3c57a560b fix: travis 2018-08-27 23:49:11 +08:00
harttle 5378f2709b test: cover all 2018-08-27 23:27:42 +08:00
harttle d6876bd9ec refactor: bundle template.js respectively 2018-08-27 21:37:39 +08:00
harttle 31c39561c9 feature: get nyc, babel and coveralls working 2018-08-26 21:54:35 +08:00
harttle d828c4021e fix: unit test on node6.x 2018-08-21 01:21:30 +08:00
harttle 4d4a2d04ec refactor 2018-08-21 01:18:13 +08:00
harttle bc9d8f92af refactor: import rollup 2018-08-20 23:58:41 +08:00
harttle 4ece4e208f 5.3.0-0 2018-08-17 01:34:57 +08:00
harttle 4ad3d2a52b modified: .eslintignore 2018-08-17 01:34:07 +08:00
harttle fa7cd8f4ff refactor: import babelify 2018-08-17 01:32:16 +08:00
harttle 87360d5207 refactor: mv es5 files to build/ 2018-08-16 23:20:13 +08:00
harttle 19891b2df0 refactor: es6 building and linting 2018-08-16 23:14:12 +08:00
harttle 5f634b0b5e refactor: moving all ES6 files to src/, working on #83 2018-08-16 00:22:46 +08:00
harttle 9f597843c9 5.2.0 2018-08-14 00:12:42 +08:00
harttle 887b736f39 test cases for stringify 2018-08-14 00:11:50 +08:00
harttle 7a3689067b feature: support toLiquid, working on #81 2018-08-14 00:11:50 +08:00
harttle 5b43520d78 feature: variable lookup respects to to_liquid, #81 2018-08-14 00:11:50 +08:00
harttle ea38a9e1f5 refactor: test/render.js use local scope 2018-08-14 00:11:50 +08:00
harttle fa5b731daf fix string type checking and circular reference, working on #81 2018-08-14 00:11:50 +08:00
harttle 96829b5293 fix: express demo, fixes #79 2018-07-25 21:51:42 +08:00
harttle 4cf7215a67 5.1.1 2018-07-24 19:39:12 +08:00
harttle 50006db26d fix: test/util/strftime.js 2018-07-24 19:38:47 +08:00
harttle 2d81223d99 update outdated packages 2018-07-24 19:37:21 +08:00
harttle 3038115c21 5.1.0 2018-07-24 14:53:47 +08:00
harttle fdbf4b838a add package.lock 2018-07-24 14:53:28 +08:00
harttle 7ab0e96419 feature: template string for {%include%} argument, #72 2018-07-24 14:49:23 +08:00
harttle 48484fe52f 5.0.2 2018-07-21 23:42:18 +08:00
harttle 14d1956232 test case for _.forOwn 2018-07-21 23:23:25 +08:00
harttle c3e7859cdd fix: increment/decrement independent from capture, #76 2018-07-21 23:19:28 +08:00
harttle c3de3fbb19 fix: post-increment, pre-decrement working on #76 2018-07-21 22:59:52 +08:00
harttle b5cfd2d2c5 fix: {%assign%} now adds a shading scope 2018-07-21 21:30:40 +08:00
harttle 36f84e4b3c refactor: pop the same context as the pushed one 2018-07-21 17:12:46 +08:00
harttle 63b5658604 refactor: src/scope.js 2018-07-21 17:02:18 +08:00
Ryan KennedyandJun Yang c79700ef1a fix: correctly understand variables with question marks
Fixes #77
2018-07-18 10:15:43 +08:00
harttle 6755462056 5.0.1 2018-07-16 15:04:40 +08:00
harttle 02806b2257 fix #75 2018-07-16 15:02:31 +08:00
harttle d0fb5ccece 5.0.0 2018-07-16 13:41:57 +08:00
harttle b7144f9b75 fix: linting 2018-07-07 01:22:40 +08:00
harttle 88fc05732f fix: tablerow cols defaults to 0, #74 2018-07-07 01:18:11 +08:00
Jun Yang 44b1aac096 remove any-promise, working on #73 2018-06-23 21:55:23 +08:00
Jun Yang 42043b6944 4.0.0 2018-05-12 23:10:36 +08:00
Jun Yang 61f146432d fix #59, divide numbers as it is 2018-05-12 22:58:43 +08:00
Jun Yang 220b705b73 3.1.3 2018-05-12 22:06:35 +08:00
Jun Yang ef85bd9192 fix #67: forloop.last, forloop.rindex, forloop.rindex0 incorrect if loop has a limit 2018-05-12 22:05:16 +08:00
Paul Robert LloydandJun Yang 8e9e10fdb4 Ensure strip_html filter uses same regex as Ruby Liquid 2018-05-09 10:41:25 +08:00
Jun Yang f668a5cc41 3.1.2 2018-04-07 19:49:46 +08:00
Jun Yang 098f5164e7 fix: linting 2018-04-07 19:48:46 +08:00
Jun Yang 432f878bb6 fix: support comma-separated arguments for static partials, fixes #62 2018-04-07 19:45:57 +08:00
Cory MawhorterandJun Yang aa54dad36e fix dupe name bug 2018-04-07 19:36:50 +08:00
Jun Yang c6ff1f7911 3.1.1 2018-03-05 01:34:00 +08:00
Jun Yang 11355cbf09 refactor: remove makefile 2018-03-05 01:31:12 +08:00
Jun Yang 7ccd0cb1e5 fix: branch coverage 2018-03-05 01:20:43 +08:00
Jun Yang 4326c223f3 fix #61: static filename not parsed for subdirectories 2018-03-05 00:58:26 +08:00
Jun Yang 78b6e35fbf fix: file path asserts for windows 2018-03-03 20:01:24 +08:00
Jun YangandGitHub e275368cb3 Update README.md 2018-01-17 11:01:58 +08:00
Jun YangandGitHub ca2b16a583 Update README.md 2018-01-17 10:48:05 +08:00
Jun YangandGitHub 86d0529a5e Update README.md 2018-01-17 10:47:11 +08:00
Jun YangandGitHub 400b93c88d Update README.md 2018-01-17 10:44:11 +08:00
harttle 22b41fd1a8 3.1.0 2018-01-12 10:55:38 +08:00
ChenLandJun Yang d7c7f32d4b make dist 2018-01-12 10:53:43 +08:00
ChenLandJun Yang 925df9a9b5 100% coverage 2018-01-12 10:53:43 +08:00
ChenLandJun Yang 7b696ed0d2 low version, skip tests 2018-01-12 10:53:43 +08:00
ChenLandJun Yang c55f0234eb Add xhr support for render file in browser. 2018-01-12 10:53:43 +08:00
harttle eee5649a47 fix package.json syntax 2017-12-31 12:32:13 +08:00
harttle 1048f4e0ab add engine spec 2017-12-31 12:29:32 +08:00
harttle 5c6d05092f fix: remove let for nodejs 4.x 2017-12-29 12:33:10 +08:00
harttle 900664a26d test cases for #53 2017-12-29 12:17:52 +08:00
harttle 757a06ee83 fix linting 2017-12-29 12:14:01 +08:00
harttle 9f6e9f2f3f 3.0.0 2017-12-23 21:36:37 +08:00
harttle 0f9adfb067 change: remove deprecated features, coverall 2017-12-23 21:31:55 +08:00
harttle dabde0e9e4 2.2.1 2017-12-23 13:01:28 +08:00
harttle bd4e851b3c update babelify 2017-12-23 12:57:19 +08:00
harttle 1d2aece687 2.2.0 2017-12-21 14:10:42 +08:00
harttle ace271c7f0 feature: support static filepath resolving by options.dynamicPartials,
fix #51
2017-12-21 14:09:30 +08:00
Sami KukkonenandJun Yang 4cbfa6d204 Ignore "fs" module in browser environments 2017-12-21 13:09:21 +08:00
harttle 3153f1d4bb 2.1.4 2017-12-10 01:35:21 +08:00
harttle 9cd4f3d904 modified: README.md 2017-12-10 01:35:06 +08:00
harttle 8dd1b3ba99 2.1.3 2017-12-10 01:26:46 +08:00
harttle 11de73a7b1 update doc 2017-12-10 00:30:13 +08:00
harttle 0325eacddf 2.1.2 2017-12-08 10:42:27 +08:00
harttle a21fcf6f87 fix: compatible to nodejs<=4 2017-12-08 10:42:00 +08:00
harttle 7bb2ee2213 2.1.1 2017-12-08 00:29:09 +08:00
harttle b24582c2c4 remove debug message, working on #50 2017-12-08 00:28:51 +08:00
harttle 49cb7a8c36 2.1.0 2017-12-08 00:25:44 +08:00
harttle a4126e7f10 fix: typo in scope.get("liquid") error message, fixes #50 2017-12-08 00:24:23 +08:00
harttle 5196d6ad56 feature: date filter supports utc string now, fixes #49 2017-12-08 00:22:56 +08:00
harttle 6082bf4757 2.0.3 2017-11-27 00:00:09 +08:00
harttle 8efb41a631 use isTruthy for and/or operators, fixes #47 2017-11-26 23:59:50 +08:00
harttle d348edac14 2.0.2 2017-11-06 00:16:51 +08:00
harttle be00f1d385 feature: treat top-level content as anonymous block, fixes #45 2017-11-06 00:14:33 +08:00
harttle 4e132ca1c5 tags: use scope.opts insteadof scope.get('liquid') 2017-11-04 10:46:15 +08:00
harttle 329aea6bd6 2.0.1 2017-10-31 00:11:35 +08:00
harttle 23e7424f9d change: default extname to "", working for #41 2017-10-31 00:10:45 +08:00
harttle 8241625be4 remove publish from version script 2017-10-30 02:24:08 +08:00
harttle d36ec17621 2.0.0 2017-10-30 02:23:36 +08:00
harttle 485424cc89 feature: concat filter 2017-10-30 02:22:56 +08:00
harttle a239389044 docs for #41 2017-10-30 02:07:07 +08:00
harttle e8fa8d32f5 feature: separate options for value/tag trimming, working on #17 2017-10-30 01:46:31 +08:00
harttle 502426f621 mv whiteSpaceCtrl to a separate file 2017-10-30 00:36:21 +08:00
harttle 8c77fc5a3d fix: whiteSpace Ctrl with compliance to shopify/liquid, working on #17 2017-10-30 00:09:29 +08:00
harttle be17d7443c 1.9.7 2017-10-21 10:50:44 +08:00
Mehdi JafferyandJun Yang 118624ca7d Fix to make for tag iterate objects like Shopify liquid.
Ref: https://github.com/Shopify/liquid/wiki/Liquid-for-Designers#allowed-collection-types
2017-10-18 05:41:43 -05:00
harttle d08ad6dc97 fix: error.stack assertion in v8.5 2017-10-06 12:32:06 +08:00
harttle e22870f5d7 fix: broken unit test by UTC time parsing behaviour change 2017-10-06 12:16:03 +08:00
harttle bd6706cf4d update outdated 2017-10-05 08:32:32 +08:00
harttle b71928ffd4 refactor: format 2017-10-05 08:21:32 +08:00
130 changed files with 15885 additions and 7948 deletions
+4
View File
@@ -0,0 +1,4 @@
node_modules
dist
build
coverage
+6 -1
View File
@@ -1,11 +1,16 @@
{
"extends": "standard",
"env": {
"es6": true,
"browser": true,
"node": true
},
"plugins": [
"standard",
"promise"
]
],
"rules": {
"no-var": 2,
"prefer-const": 2
}
}
+8 -34
View File
@@ -1,40 +1,14 @@
# Logs
logs
# logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# tests
coverage/
.nyc_output/
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# modules
node_modules/
build/
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules
jspm_packages
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
# vim
# editors
.*.swp
+3 -1
View File
@@ -1 +1,3 @@
test/
/coverage
/test
.*
+8 -3
View File
@@ -1,7 +1,12 @@
language: node_js
node_js:
- "5"
- "8"
- "6"
- "4"
before_script:
- npm install -g mocha
after_script:
- npm run lcov && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage
script:
- if (( $TRAVIS_NODE_VERSION >= 6 )); then npm run test; fi
- npm run e2e
after_success:
- if (( $TRAVIS_NODE_VERSION >= 6 )); then npm run coveralls; fi
+114 -100
View File
@@ -1,59 +1,79 @@
# liquidjs
[![npm](https://img.shields.io/npm/v/liquidjs.svg)](https://www.npmjs.org/package/liquidjs)
[![npm](https://img.shields.io/npm/dm/liquidjs.svg)](https://www.npmjs.org/package/liquidjs)
[![Build Status](https://travis-ci.org/harttle/liquidjs.svg?branch=master)](https://travis-ci.org/harttle/liquidjs)
[![Coveralls](https://img.shields.io/coveralls/harttle/liquidjs.svg)](https://coveralls.io/github/harttle/liquidjs?branch=master)
[![GitHub issues](https://img.shields.io/github/issues-closed/harttle/liquidjs.svg)](https://github.com/harttle/liquidjs/issues)
[![GitHub contributors](https://img.shields.io/github/contributors/harttle/liquidjs.svg)](https://github.com/harttle/liquidjs/graphs/contributors)
[![David](https://img.shields.io/david/harttle/liquidjs.svg)](https://david-dm.org/harttle/liquidjs)
[![David Dev](https://img.shields.io/david/dev/harttle/liquidjs.svg)](https://david-dm.org/harttle/liquidjs?type=dev)
[![DUB](https://img.shields.io/dub/l/vibe-d.svg)](https://github.com/harttle/liquidjs/blob/master/LICENSE)
A Liquid engine implementation for both Node.js and browsers, with all [shopify/liquid][shopify/liquid] features.
Formerly known as shopify-liquid.
This is a liquid implementation for both Node.js and browsers. Website: <http://harttle.github.io/liquidjs/>, Live Demo: <https://jsfiddle.net/6u40xbzs/>
Live Demo: <http://harttle.com/liquidjs/>
**Features**
> The Liquid template engine is implemented in Ruby originally,
> which is used by [Jekyll][jekyll] and [Github Pages][gh].
* 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
Features:
**Differences**
* A wide range of [filters](https://github.com/harttle/liquidjs/wiki/Builtin-Filters) and [tags](https://github.com/harttle/liquidjs/wiki/Builtin-Tags)
* Easy tag/filter registration, allows async tags
* [any-promise][any-promise]
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:
API Reference:
* 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).
* Along with [.to_liquid()](https://github.com/Shopify/liquid/wiki/Introduction-to-Drops), we provide an alias `.toLiquid()` to align with your code styles.
* Builtin Tags: <https://github.com/harttle/liquidjs/wiki/Builtin-Tags>
* Builtin Filters: <https://github.com/harttle/liquidjs/wiki/Builtin-Filters>
* Operators: <https://github.com/harttle/liquidjs/wiki/Operators>
* Whitespace Control: <https://github.com/harttle/liquidjs/wiki/Whitespace-Control>
## TOC
Installation:
```bash
npm install --save liquidjs
```
* 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('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
@@ -61,43 +81,17 @@ engine.render(tpl, {name: 'alice'})
```javascript
var engine = Liquid({
root: path.resolve(__dirname, 'views/'), // dirs to lookup layouts/includes
extname: '.liquid' // the default extname used for 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"
```
## 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. 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`.
* `trim_right` is used to strip blank characters (including ` `, `\t`, and `\r`) from the right of tags (`{% %}`) until `\n` (inclusive). Defaults to `false`.
* `trim_left` is similiar to `trim_right`, whereas the `\n` is exclusive. Defaults to `false`. See [Whitespace Control][whitespace control] for details.
* `greedy` is used to specify whether `trim_left`/`trim_right` is greedy. When set to `true`, all successive blank characters including `\n` will be trimed regardless of line breaks. Defaults to `false`.
## Use with Express.js
```javascript
@@ -107,41 +101,25 @@ 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 liquidjs'
};
engine.parseAndRender(src, ctx)
.then(function(html) {
// html === Welcome to liquidjs
});
</script>
</body>
</html>
```
* [Releases][releases] page for liquidjs, or
* unpkg.com: <https://unpkg.com/liquidjs/dist/liquid.min.js>
Note: In [IE and Android UC][caniuse-promises] browser, you need a Promise implementation
registered to [any-promise][any-promise].
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
@@ -162,7 +140,7 @@ color: 'red' shape: 'circle'
color: 'yellow' shape: 'square'
```
## Layouts
## Layout Templates (Extends)
```
// file: default-layout.liquid
@@ -186,16 +164,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/liquidjs/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
@@ -212,13 +225,10 @@ engine.registerTag('upper', {
});
```
> See existing tag implementations: <https://github.com/harttle/liquidjs/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. Write a [test][test] to define the feature you want.
2. File an issue, or optionally:
3. Get your test pass and make 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
@@ -230,3 +240,7 @@ engine.registerTag('upper', {
[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
+1
View File
@@ -0,0 +1 @@
access time: {{date|date: "%Y-%m-%d %H:%M:%S"}}
+1
View File
@@ -0,0 +1 @@
<h2>Welcome to {{ name | capitalize}}, {% include 'date.html' %}</h2>
+12 -9
View File
@@ -1,26 +1,29 @@
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="UTF-8">
<title></title>
<title>liquidjs for the browser</title>
<script src="../../dist/liquid.js"></script>
</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({
extname: '.html',
cache: true
});
var src = '<h2>Welcome to {{ name | capitalize}}, ' +
'access time: {{date|date: "%Y-%m-%d %H:%M:%S"}}&lt;/h2>';
var ctx = {
name: 'Liquid',
date: new Date()
};
engine.parseAndRender(src, ctx)
.then(function(html) {
document.getElementById('header').innerHTML = html;
return engine.renderFile('hello', ctx);
})
.then(function(html) {
document.body.innerHTML += html
});
</script>
</body>
+8 -8
View File
@@ -1,18 +1,18 @@
var express = require('express')
var app = express()
var Liquid = require('../..')
const express = require('express')
const Liquid = require('../..')
var engine = Liquid({
root: __dirname, // for layouts and partials
let app = express()
let engine = 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.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']
let todos = ['fork and clone', 'make it better', 'make a pull request']
res.render('todolist', {
todos: todos,
title: 'Welcome to liquidjs!'
+3 -4
View File
@@ -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('Express running: http://localhost:3000')
})
+2 -2
View File
@@ -1,8 +1,8 @@
{% layout 'layout' %}
<ul>
{% for todo in todolist %}
<li>{% include 'todo' id=forloop.index %}</li>
{% for todo in todos %}
<li>{% include 'todo', id:forloop.index %}</li>
{% endfor %}
</ul>
+12
View File
@@ -0,0 +1,12 @@
const Liquid = require('../..')
const engine = new Liquid({
root: __dirname,
extname: '.liquid'
})
const ctx = {
todos: ['fork and clone', 'make it better', 'make a pull request'],
title: 'Welcome to liquidjs!'
}
engine.renderFile('todolist', ctx).then(console.log)
+5
View File
@@ -0,0 +1,5 @@
<ul>
{% for todo in todos %}
<li>{{forloop.index}} - {{todo}}</li>
{% endfor %}
</ul>
View File
+3623
View File
File diff suppressed because it is too large Load Diff
+1
View File
File diff suppressed because one or more lines are too long
+3399 -2353
View File
File diff suppressed because it is too large Load Diff
+1
View File
File diff suppressed because one or more lines are too long
+2 -1
View File
File diff suppressed because one or more lines are too long
+1
View File
File diff suppressed because one or more lines are too long
-144
View File
@@ -1,144 +0,0 @@
const Scope = require('./src/scope')
const _ = require('./src/util/underscore.js')
const assert = require('./src/util/assert.js')
const tokenizer = require('./src/tokenizer.js')
const statFileAsync = require('./src/util/fs.js').statFileAsync
const readFileAsync = require('./src/util/fs.js').readFileAsync
const path = require('path')
const Render = require('./src/render.js')
const lexical = require('./src/lexical.js')
const Tag = require('./src/tag.js')
const Filter = require('./src/filter.js')
const Parser = require('./src/parser')
const Syntax = require('./src/syntax.js')
const tags = require('./tags')
const filters = require('./filters')
const Promise = require('any-promise')
const anySeries = require('./src/util/promise.js').anySeries
const Errors = require('./src/util/error.js')
var _engine = {
init: function (tag, filter, options) {
if (options.cache) {
this.cache = {}
}
this.options = options
this.tag = tag
this.filter = filter
this.parser = Parser(tag, filter)
this.renderer = Render()
tags(this)
filters(this)
return this
},
parse: function (html, filepath) {
var tokens = tokenizer.parse(html, filepath, this.options)
return this.parser.parse(tokens)
},
render: function (tpl, ctx, opts) {
opts = _.assign({}, this.options, opts)
var scope = Scope.factory(ctx, opts)
return this.renderer.renderTemplates(tpl, scope)
},
parseAndRender: function (html, ctx, opts) {
return Promise.resolve()
.then(() => this.parse(html))
.then(tpl => this.render(tpl, ctx, opts))
},
renderFile: function (filepath, ctx, opts) {
opts = _.assign({}, opts)
return this.getTemplate(filepath, opts.root)
.then(templates => this.render(templates, ctx, opts))
},
evalOutput: function (str, scope) {
var tpl = this.parser.parseOutput(str.trim())
return this.renderer.evalOutput(tpl, scope)
},
registerFilter: function (name, filter) {
return this.filter.register(name, filter)
},
registerTag: function (name, tag) {
return this.tag.register(name, tag)
},
lookup: function (filepath, root) {
root = this.options.root.concat(root || [])
root = _.uniq(root)
var paths = root.map(root => path.resolve(root, filepath))
return anySeries(paths, path => statFileAsync(path).then(() => path))
.catch((e) => {
e.message = `${e.code}: Failed to lookup ${filepath} in: ${root}`
throw e
})
},
getTemplate: function (filepath, root) {
if (!path.extname(filepath)) {
filepath += this.options.extname
}
return this
.lookup(filepath, root)
.then(filepath => {
if (this.options.cache) {
var tpl = this.cache[filepath]
if (tpl) {
return Promise.resolve(tpl)
}
return readFileAsync(filepath)
.then(str => this.parse(str))
.then(tpl => (this.cache[filepath] = tpl))
} else {
return readFileAsync(filepath).then(str => this.parse(str, filepath))
}
})
},
express: function (opts) {
opts = opts || {}
var self = this
return function (filePath, ctx, callback) {
assert(Array.isArray(this.root) || _.isString(this.root),
'illegal views root, are you using express.js?')
opts.root = this.root
self.renderFile(filePath, ctx, opts)
.then(html => callback(null, html))
.catch(e => callback(e))
}
}
}
function factory (options) {
options = _.assign({
root: ['.'],
cache: false,
extname: '.liquid',
trim_right: false,
trim_left: false,
strict_filters: false,
strict_variables: false
}, options)
options.root = normalizeStringArray(options.root)
var engine = Object.create(_engine)
engine.init(Tag(), Filter(options), options)
return engine
}
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
}
module.exports = factory
-18
View File
@@ -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/
+4329 -2453
View File
File diff suppressed because it is too large Load Diff
+76 -28
View File
@@ -1,22 +1,31 @@
{
"name": "liquidjs",
"version": "1.9.6",
"description": "A Liquid template engine for Node.js and browsers, with all shopify/liquid features.",
"main": "index.js",
"version": "6.0.1",
"description": "Liquid template engine by pure JavaScript: compatible to shopify, easy to extend.",
"main": "dist/liquid.common.js",
"module": "src/index.js",
"browser": "dist/liquid.js",
"scripts": {
"lint": "eslint src/ test/",
"test": "npm run lint && mocha --recursive",
"coverage": "NODE_ENV=test istanbul cover --report html ./node_modules/mocha/bin/_mocha -- -R spec --recursive",
"lcov": "NODE_ENV=test istanbul cover --report lcovonly ./node_modules/mocha/bin/_mocha -- -R spec --recursive",
"dist": "make dist",
"preversion": "npm test",
"lint": "eslint src/ test/ *.js",
"dev": "mocha test/unit",
"test": "cross-env NODE_ENV=test nyc --reporter=html mocha test/unit",
"e2e": "mocha test/e2e",
"coveralls": "nyc report --reporter=text-lcov | coveralls",
"dist": "rollup -c && ls -lh dist",
"demo:browser": "echo open http://localhost:8080/demo/browser && http-server -c-1",
"demo:nodejs": "node ./demo/nodejs/index.js",
"demo:express": "cd ./demo/express/ && npm start",
"preversion": "npm run lint && npm test",
"version": "npm run dist && git add -A dist",
"postversion": "git push && git push --tags && npm publish"
"postversion": "git push --tags"
},
"repository": {
"type": "git",
"url": "git+https://github.com/harttle/liquidjs.git"
},
"engines": {
"node": ">=4.8.7"
},
"keywords": [
"liquid",
"template engine",
@@ -30,30 +39,69 @@
"url": "https://github.com/harttle/liquidjs/issues"
},
"homepage": "https://github.com/harttle/liquidjs#readme",
"dependencies": {
"any-promise": "^1.3.0"
},
"devDependencies": {
"babel-preset-es2015": "^6.24.1",
"babelify": "^7.3.0",
"browserify": "^14.4.0",
"babel-core": "^6.26.3",
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-istanbul": "^4.1.6",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"babel-runtime": "^6.26.0",
"chai": "^4.1.2",
"chai-as-promised": "^7.1.1",
"coveralls": "^2.13.1",
"eslint": "^4.6.1",
"eslint-config-standard": "^10.2.1",
"coveralls": "^3.0.0",
"cross-env": "^5.2.0",
"eslint": "^5.2.0",
"eslint-config-standard": "^11.0.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-mocha": "^4.11.0",
"eslint-plugin-node": "^5.1.1",
"eslint-plugin-mocha": "^5.1.0",
"eslint-plugin-node": "^7.0.1",
"eslint-plugin-promise": "^3.5.0",
"eslint-plugin-standard": "^3.0.1",
"express": "^4.15.4",
"istanbul": "^0.4.5",
"mocha": "^3.5.3",
"express": "^4.16.1",
"http-server": "^0.11.1",
"jsdom": "^11.5.1",
"mocha": "^5.2.0",
"mock-fs": "^4.4.1",
"sinon": "^3.2.1",
"sinon-chai": "^2.13.0",
"supertest": "^3.0.0",
"uglify-js": "^3.1.0"
"nyc": "^13.0.1",
"regenerator-runtime": "^0.12.1",
"rollup": "^0.64.1",
"rollup-plugin-alias": "^1.4.0",
"rollup-plugin-babel": "^3.0.7",
"rollup-plugin-node-resolve": "^3.3.0",
"rollup-plugin-shim": "^1.0.0",
"rollup-plugin-uglify": "^4.0.0",
"sinon": "^6.1.4",
"sinon-chai": "^3.2.0",
"supertest": "^3.0.0"
},
"nyc": {
"require": [
"babel-core/register"
],
"sourceMap": false,
"instrument": false
},
"babel": {
"presets": [
"env"
],
"plugins": [
[
"transform-runtime",
{
"helpers": false,
"polyfill": false,
"regenerator": true,
"moduleName": "babel-runtime"
}
]
],
"env": {
"test": {
"plugins": [
"istanbul"
]
}
}
}
}
+75
View File
@@ -0,0 +1,75 @@
import shim from 'rollup-plugin-shim'
import alias from 'rollup-plugin-alias'
import babel from 'rollup-plugin-babel'
import {uglify} from 'rollup-plugin-uglify'
import pkg from './package.json'
import nodeResolve from 'rollup-plugin-node-resolve'
const fake = {fs: `export default {}`, path: `export default {}`}
const version = process.env.VERSION || pkg.version
const sourcemap = true
const banner = `/*
* liquidjs@${version}, https://github.com/liquidjs
* (c) 2016-${new Date().getFullYear()} harttle
* Released under the MIT License.
*/`
const treeshake = {
propertyReadSideEffects: false
}
const input = 'src/index.js'
const babelConf = {
babelrc: false,
'presets': [['env', {'modules': false}]],
'plugins': ['external-helpers']
}
export default [{
output: [{
file: 'dist/liquid.common.js',
name: 'Liquid',
format: 'cjs',
sourcemap,
banner
}],
external: ['path', 'fs'],
plugins: [
nodeResolve(),
babel(babelConf)
],
treeshake,
input
}, {
output: [{
file: 'dist/liquid.js',
name: 'Liquid',
format: 'umd',
sourcemap,
banner
}],
plugins: [
shim(fake),
alias({
'./template': './template-browser'
}),
nodeResolve(),
babel(babelConf)
],
treeshake,
input
}, {
output: [{
file: 'dist/liquid.min.js',
name: 'Liquid',
format: 'umd',
sourcemap
}],
plugins: [
shim(fake),
nodeResolve(),
babel(babelConf),
uglify()
],
treeshake,
input
}]
+21 -19
View File
@@ -1,27 +1,27 @@
const lexical = require('./lexical.js')
const Syntax = require('./syntax.js')
const assert = require('./util/assert.js')
const _ = require('./util/underscore.js')
import * as lexical from './lexical.js'
import {evalValue} from './syntax.js'
import assert from './util/assert.js'
import {assign, create} from './util/underscore.js'
var valueRE = new RegExp(`${lexical.value.source}`, 'g')
const valueRE = new RegExp(`${lexical.value.source}`, 'g')
module.exports = function (options) {
options = _.assign({}, options)
var filters = {}
export default function (options) {
options = assign({}, options)
let filters = {}
var _filterInstance = {
const _filterInstance = {
render: function (output, scope) {
var args = this.args.map(arg => Syntax.evalValue(arg, scope))
const args = this.args.map(arg => evalValue(arg, scope))
args.unshift(output)
return this.filter.apply(null, args)
},
parse: function (str) {
var match = lexical.filterLine.exec(str)
let match = lexical.filterLine.exec(str)
assert(match, 'illegal filter: ' + str)
var name = match[1]
var argList = match[2] || ''
var filter = filters[name]
const name = match[1]
const argList = match[2] || ''
const filter = filters[name]
if (typeof filter !== 'function') {
if (options.strict_filters) {
throw new TypeError(`undefined filter: ${name}`)
@@ -32,11 +32,13 @@ module.exports = function (options) {
return this
}
var args = []
const args = []
while ((match = valueRE.exec(argList.trim()))) {
var v = match[0]
var re = new RegExp(`${v}\\s*:`, 'g')
re.test(match.input) ? args.push(`'${v}'`) : args.push(v)
const v = match[0]
const re = new RegExp(`${v}\\s*:`, 'g')
const keyMatch = re.exec(match.input)
const currentMatchIsKey = keyMatch && keyMatch.index === match.index
currentMatchIsKey ? args.push(`'${v}'`) : args.push(v)
}
this.name = name
@@ -48,7 +50,7 @@ module.exports = function (options) {
}
function construct (str) {
var instance = Object.create(_filterInstance)
const instance = create(_filterInstance)
return instance.parse(str)
}
+28 -19
View File
@@ -1,15 +1,15 @@
const strftime = require('./src/util/strftime.js')
const _ = require('./src/util/underscore.js')
const isTruthy = require('./src/syntax.js').isTruthy
import strftime from './util/strftime.js'
import * as _ from './util/underscore.js'
import {isTruthy} from './syntax.js'
var escapeMap = {
const escapeMap = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&#34;',
"'": '&#39;'
}
var unescapeMap = {
const unescapeMap = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
@@ -17,17 +17,23 @@ var unescapeMap = {
'&#39;': "'"
}
var filters = {
const 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),
'concat': (v, arg) => Array.prototype.concat.call(v, arg),
'date': (v, arg) => {
if (v === 'now') v = new Date()
return v instanceof Date ? strftime(v, arg) : ''
let 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) => Math.floor(v / arg),
'divided_by': (v, arg) => v / arg,
'downcase': v => v.toLowerCase(),
'escape': escape,
@@ -35,7 +41,7 @@ var filters = {
'first': v => v[0],
'floor': v => Math.floor(v),
'join': (v, arg) => v.join(arg),
'last': v => v[v.length - 1],
'last': v => _.last(v),
'lstrip': v => stringify(v).replace(/^\s+/, ''),
'map': (arr, arg) => arr.map(v => v[arg]),
'minus': bindFixed((v, arg) => v - arg),
@@ -50,7 +56,7 @@ var filters = {
'replace_first': (v, arg1, arg2) => stringify(v).replace(arg1, arg2),
'reverse': v => v.reverse(),
'round': (v, arg) => {
var amp = Math.pow(10, arg || 0)
const amp = Math.pow(10, arg || 0)
return Math.round(v * amp, arg) / amp
},
'rstrip': str => stringify(str).replace(/\s+$/, ''),
@@ -60,7 +66,7 @@ var filters = {
'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_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) => {
@@ -72,13 +78,13 @@ var filters = {
},
'truncatewords': (v, l, o) => {
if (o === undefined) o = '...'
var arr = v.split(' ')
var ret = arr.slice(0, l).join(' ')
const arr = v.split(' ')
let ret = arr.slice(0, l).join(' ')
if (arr.length > l) ret += o
return ret
},
'uniq': function (arr) {
var u = {}
const u = {}
return (arr || []).filter(val => {
if (u.hasOwnProperty(val)) {
return false
@@ -100,7 +106,7 @@ function unescape (str) {
}
function getFixed (v) {
var p = (v + '').split('.')
const p = (v + '').split('.')
return (p.length > 1) ? p[1].length : 0
}
@@ -114,14 +120,17 @@ function stringify (obj) {
function bindFixed (cb) {
return (l, r) => {
var f = getMaxFixed(l, r)
const f = getMaxFixed(l, r)
return cb(l, r).toFixed(f)
}
}
function registerAll (liquid) {
function isValidDate (date) {
return date instanceof Date && !isNaN(date.getTime())
}
export default function registerAll (liquid) {
return _.forOwn(filters, (func, name) => liquid.registerFilter(name, func))
}
registerAll.filters = filters
module.exports = registerAll
+130
View File
@@ -0,0 +1,130 @@
import 'regenerator-runtime/runtime'
import * as Scope from './scope'
import * as template from './template'
import * as _ from './util/underscore.js'
import assert from './util/assert.js'
import * as tokenizer from './tokenizer.js'
import Render from './render.js'
import Tag from './tag.js'
import Filter from './filter.js'
import Parser from './parser'
import {isTruthy, isFalsy, evalExp, evalValue} from './syntax.js'
import {ParseError, TokenizationError, RenderBreakError, AssertionError} from './util/error.js'
import tags from './tags/index.js'
import filters from './filters.js'
const _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, Liquid)
filters(this, Liquid)
return this
},
parse: function (html, filepath) {
const tokens = tokenizer.parse(html, filepath, this.options)
return this.parser.parse(tokens)
},
render: function (tpl, ctx, opts) {
opts = _.assign({}, this.options, opts)
const scope = Scope.factory(ctx, opts)
return this.renderer.renderTemplates(tpl, scope)
},
parseAndRender: async function (html, ctx, opts) {
const tpl = await this.parse(html)
return this.render(tpl, ctx, opts)
},
getTemplate: async function (file, root) {
const filepath = await template.resolve(file, root, this.options)
return this.respectCache(filepath, async () => {
const str = await template.read(filepath)
return this.parse(str, filepath)
})
},
renderFile: async function (file, ctx, opts) {
opts = _.assign({}, opts)
const templates = await this.getTemplate(file, opts.root)
return this.render(templates, ctx, opts)
},
respectCache: async function (key, getter) {
const cacheEnabled = this.options.cache
if (cacheEnabled && this.cache[key]) {
return this.cache[key]
}
const value = await getter()
if (cacheEnabled) {
this.cache[key] = value
}
return value
},
evalValue: function (str, scope) {
const 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)
},
express: function (opts) {
opts = opts || {}
const self = this
return function (filePath, ctx, cb) {
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 => cb(null, html), cb)
}
}
}
function normalizeStringArray (value) {
if (_.isArray(value)) return value
if (_.isString(value)) return [value]
throw new TypeError('illegal root: ' + value)
}
export default function Liquid (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)
const engine = _.create(_engine)
engine.init(Tag(), Filter(options), options)
return engine
}
Liquid.isTruthy = isTruthy
Liquid.isFalsy = isFalsy
Liquid.evalExp = evalExp
Liquid.evalValue = evalValue
Liquid.Types = {
ParseError,
TokenizationError,
RenderBreakError,
AssertionError,
AssignScope: {},
CaptureScope: {},
IncrementScope: {},
DecrementScope: {}
}
+39 -69
View File
@@ -1,76 +1,76 @@
// quote related
var singleQuoted = /'[^']*'/
var doubleQuoted = /"[^"]*"/
var quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
var quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`)
const singleQuoted = /'[^']*'/
const doubleQuoted = /"[^"]*"/
export const quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
export const quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`)
// basic types
var integer = /-?\d+/
var number = /-?\d+\.?\d*|\.?\d+/
var bool = /true|false/
export const integer = /-?\d+/
export const number = /-?\d+\.?\d*|\.?\d+/
export const 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})*`)
// property access
export const identifier = /[\w-]+[?]?/
export const subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`)
export const literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`)
export const 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})\\)`)
export const rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`)
export const range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`)
export const rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`)
var value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
export const 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')
export const hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`)
export const hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
// full match
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}$`)
export const tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`)
export const literalLine = new RegExp(`^${literal.source}$`, 'i')
export const variableLine = new RegExp(`^${variable.source}$`)
export const numberLine = new RegExp(`^${number.source}$`)
export const boolLine = new RegExp(`^${bool.source}$`, 'i')
export const quotedLine = new RegExp(`^${quoted.source}$`)
export const rangeLine = new RegExp(`^${rangeCapture.source}$`)
export const integerLine = new RegExp(`^${integer.source}$`)
// filter related
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}$`)
export const valueDeclaration = new RegExp(`(?:${identifier.source}\\s*:\\s*)?${value.source}`)
export const valueList = new RegExp(`${valueDeclaration.source}(\\s*,\\s*${valueDeclaration.source})*`)
export const filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g')
export const filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`)
export const filterLine = new RegExp(`^${filterCapture.source}$`)
var operators = [
export const operators = [
/\s+or\s+/,
/\s+and\s+/,
/==|!=|<=|>=|<|>|\s+contains\s+/
]
function isInteger (str) {
export function isInteger (str) {
return integerLine.test(str)
}
function isLiteral (str) {
export function isLiteral (str) {
return literalLine.test(str)
}
function isRange (str) {
export function isRange (str) {
return rangeLine.test(str)
}
function isVariable (str) {
export function isVariable (str) {
return variableLine.test(str)
}
function matchValue (str) {
export function matchValue (str) {
return value.exec(str)
}
function parseLiteral (str) {
var res = str.match(numberLine)
export function parseLiteral (str) {
let res = str.match(numberLine)
if (res) {
return Number(str)
}
@@ -84,33 +84,3 @@ function parseLiteral (str) {
}
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
}
+16 -16
View File
@@ -1,17 +1,17 @@
var operators = {
'==': (l, r) => l === r,
'!=': (l, r) => l !== r,
'>': (l, r) => l !== null && r !== null && l > r,
'<': (l, r) => l !== null && r !== null && l < r,
'>=': (l, r) => l !== null && r !== null && l >= r,
'<=': (l, r) => l !== null && r !== null && l <= r,
'contains': (l, r) => {
if (!l) return false
if (typeof l.indexOf !== 'function') return false
return l.indexOf(r) > -1
},
'and': (l, r) => l && r,
'or': (l, r) => l || r
export default 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)
}
}
module.exports = operators
+22 -21
View File
@@ -1,9 +1,10 @@
const lexical = require('./lexical.js')
const ParseError = require('./util/error.js').ParseError
const assert = require('./util/assert.js')
import * as lexical from './lexical.js'
import {create} from './util/underscore.js'
import {ParseError} from './util/error.js'
import assert from './util/assert.js'
module.exports = function (Tag, Filter) {
var stream = {
export default function (Tag, Filter) {
const stream = {
init: function (tokens) {
this.tokens = tokens
this.handlers = {}
@@ -14,7 +15,7 @@ module.exports = function (Tag, Filter) {
return this
},
trigger: function (event, arg) {
var h = this.handlers[event]
const h = this.handlers[event]
if (typeof h === 'function') {
h(arg)
return true
@@ -22,14 +23,14 @@ module.exports = function (Tag, Filter) {
},
start: function () {
this.trigger('start')
var token
let 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)
const template = parseToken(token, this.tokens)
this.trigger('template', template)
}
if (!this.stopRequested) this.trigger('end')
@@ -42,8 +43,8 @@ module.exports = function (Tag, Filter) {
}
function parse (tokens) {
var token
var templates = []
let token
const templates = []
while ((token = tokens.shift())) {
templates.push(parseToken(token, tokens))
}
@@ -52,11 +53,11 @@ module.exports = function (Tag, Filter) {
function parseToken (token, tokens) {
try {
var tpl = null
let tpl = null
if (token.type === 'tag') {
tpl = parseTag(token, tokens)
} else if (token.type === 'output') {
tpl = parseOutput(token.value)
} else if (token.type === 'value') {
tpl = parseValue(token.value)
} else { // token.type === 'html'
tpl = token
}
@@ -72,27 +73,27 @@ module.exports = function (Tag, Filter) {
return Tag.construct(token, tokens)
}
function parseOutput (str) {
var match = lexical.matchValue(str)
assert(match, `illegal output string: ${str}`)
function parseValue (str) {
let match = lexical.matchValue(str)
assert(match, `illegal value string: ${str}`)
var initial = match[0]
const initial = match[0]
str = str.substr(match.index + match[0].length)
var filters = []
const filters = []
while ((match = lexical.filter.exec(str))) {
filters.push([match[0].trim()])
}
return {
type: 'output',
type: 'value',
initial: initial,
filters: filters.map(str => Filter.construct(str))
}
}
function parseStream (tokens) {
var s = Object.create(stream)
const s = create(stream)
return s.init(tokens)
}
@@ -100,6 +101,6 @@ module.exports = function (Tag, Filter) {
parse,
parseTag,
parseStream,
parseOutput
parseValue
}
}
+41 -47
View File
@@ -1,68 +1,62 @@
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')
import {evalExp} from './syntax.js'
import {RenderBreakError, RenderError} from './util/error.js'
import {stringify, create} from './util/underscore.js'
import assert from './util/assert.js'
var render = {
renderTemplates: function (templates, scope) {
const render = {
renderTemplates: async 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)
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)
let html = ''
for (const tpl of templates) {
try {
html += await renderTemplate.call(this, tpl)
} catch (e) {
if (e instanceof RenderBreakError) {
e.resolvedHTML = html
throw e
}
throw new RenderError(e, tpl)
}
}
return html
async function renderTemplate (template) {
if (template.type === 'tag') {
const partial = await this.renderTag(template, scope)
return partial === undefined ? '' : partial
}
if (template.type === 'value') {
return this.renderValue(template, scope)
}
return template.value
}
},
renderTag: function (template, scope) {
renderTag: async function (template, scope) {
if (template.name === 'continue') {
return Promise.reject(new RenderBreakError('continue'))
throw new RenderBreakError('continue')
}
if (template.name === 'break') {
return Promise.reject(new RenderBreakError('break'))
throw new RenderBreakError('break')
}
return template.render(scope)
},
evalOutput: function (template, scope) {
assert(scope, 'unable to evalOutput: scope undefined')
renderValue: async function (template, scope) {
const partial = this.evalValue(template, scope)
return partial === undefined ? '' : stringify(partial)
},
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))
evalExp(template.initial, scope))
}
}
function factory () {
var instance = Object.create(render)
export default function () {
const instance = create(render)
return instance
}
function stringify (val) {
if (typeof val === 'string') return val
return JSON.stringify(val)
}
module.exports = factory
+89 -106
View File
@@ -1,70 +1,81 @@
const _ = require('./util/underscore.js')
const lexical = require('./lexical.js')
const assert = require('./util/assert.js')
import * as _ from './util/underscore.js'
import * as lexical from './lexical.js'
import assert from './util/assert.js'
var Scope = {
const Scope = {
getAll: function () {
var ctx = {}
for (var i = this.scopes.length - 1; i >= 0; i--) {
_.assign(ctx, this.scopes[i])
}
return ctx
return this.contexts.reduce((ctx, val) => _.assign(ctx, val), _.create(null))
},
get: function (str) {
try {
return this.getPropertyByPath(this.scopes, str)
} catch (e) {
if (!/undefined variable/.test(e.message) || this.opts.strict_variables) {
throw e
get: function (path) {
const paths = this.propertyAccessSeq(path)
const scope = this.findContextFor(paths[0]) || _.last(this.contexts)
return paths.reduce((value, key) => this.readProperty(value, key), scope)
},
set: function (path, v) {
const paths = this.propertyAccessSeq(path)
let scope = this.findContextFor(paths[0]) || _.last(this.contexts)
paths.some((key, i) => {
if (!_.isObject(scope)) {
return true
}
}
},
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]
if (i === paths.length - 1) {
scope[key] = v
return true
}
if (undefined === scope[key]) {
scope[key] = {}
}
scope = scope[key]
})
},
unshift: function (ctx) {
assert(ctx, `trying to push ${ctx} into scopes`)
return this.scopes.unshift(ctx)
return this.contexts.unshift(ctx)
},
shift: function () {
return this.scopes.shift()
push: function (ctx) {
return this.contexts.push(ctx)
},
getPropertyByPath: function (scopes, path) {
var paths = this.propertyAccessSeq(path + '')
if (!paths.length) {
throw new TypeError('undefined variable: ' + path)
pop: function (ctx) {
if (!arguments.length) {
return this.contexts.pop()
}
var key = paths.shift()
var value = getValueFromScopes(key, scopes)
return paths.reduce(
(value, key) => {
if (_.isNil(value)) {
throw new TypeError('undefined variable: ' + key)
}
return getValueFromParent(key, value)
},
value
)
const i = this.contexts.findIndex(scope => scope === ctx)
if (i === -1) {
throw new TypeError('scope not found, cannot pop')
}
return this.contexts.splice(i, 1)[0]
},
findContextFor: function (key, filter) {
filter = filter || (() => true)
for (let i = this.contexts.length - 1; i >= 0; i--) {
const candidate = this.contexts[i]
if (!filter(candidate)) continue
if (key in candidate) {
return candidate
}
}
return null
},
readProperty: function (obj, key) {
let val
if (_.isNil(obj)) {
val = undefined
} else {
if (typeof obj.to_liquid === 'function') {
obj = obj.to_liquid()
} else if (typeof obj.toLiquid === 'function') {
obj = obj.toLiquid()
}
if (key === 'size' && (_.isArray(obj) || _.isString(obj))) {
val = obj.length
} else {
val = obj[key]
}
}
if (_.isNil(val) && this.opts.strict_variables) {
throw new TypeError(`undefined variable: ${key}`)
}
return val
},
/*
@@ -76,16 +87,17 @@ var Scope = {
* accessSeq("foo[bar.coo]") // ['foo', 'bar'], for bar.coo == 'bar'
*/
propertyAccessSeq: function (str) {
var seq = []
var name = ''
var j
var i = 0
str = String(str)
const seq = []
let name = ''
let j
let i = 0
while (i < str.length) {
switch (str[i]) {
case '[':
push()
var delemiter = str[i + 1]
const delemiter = str[i + 1]
if (/['"]/.test(delemiter)) { // foo["bar"]
j = str.indexOf(delemiter, i + 2)
assert(j !== -1, `unbalanced ${delemiter}: ${str}`)
@@ -97,7 +109,7 @@ var Scope = {
assert(j !== -1, `unbalanced []: ${str}`)
name = str.slice(i + 1, j)
if (!lexical.isInteger(name)) { // foo[bar] vs. foo[1]
name = this.get(name)
name = String(this.get(name))
}
push()
i = j + 1
@@ -113,6 +125,10 @@ var Scope = {
}
}
push()
if (!seq.length) {
throw new TypeError(`invalid path:"${str}"`)
}
return seq
function push () {
@@ -122,38 +138,9 @@ var Scope = {
}
}
function setPropertyByPath (obj, path, val) {
var paths = (path + '').replace(/\[/g, '.').replace(/\]/g, '').split('.')
for (var i = 0; i < paths.length; i++) {
var key = paths[i]
if (i === paths.length - 1) {
return (obj[key] = val)
}
if (undefined === obj[key]) obj[key] = {}
// case for readonly objects
obj = obj[key] || {}
}
}
function getValueFromParent (key, value) {
return (key === 'size' && (_.isArray(value) || _.isString(value)))
? value.length
: value[key]
}
function getValueFromScopes (key, scopes) {
for (var i = scopes.length - 1; i > -1; i--) {
var scope = scopes[i]
if (scope.hasOwnProperty(key)) {
return scope[key]
}
}
throw new TypeError('undefined variable: ' + key)
}
function matchRightBracket (str, begin) {
var stack = 1 // count of '[' - count of ']'
for (var i = begin; i < str.length; i++) {
let stack = 1 // count of '[' - count of ']'
for (let i = begin; i < str.length; i++) {
if (str[i] === '[') {
stack++
}
@@ -167,20 +154,16 @@ function matchRightBracket (str, begin) {
return -1
}
exports.factory = function (ctx, opts) {
opts = _.assign({
export function factory (ctx, opts) {
const defaultOptions = {
dynamicPartials: true,
strict_variables: false,
strict_filters: false,
blocks: {},
root: []
}, opts)
ctx = _.assign(ctx, {
liquid: opts
})
var scope = Object.create(Scope)
scope.opts = opts
scope.scopes = [ctx]
}
const scope = _.create(Scope)
scope.opts = _.assign(defaultOptions, opts)
scope.contexts = [ctx || {}]
return scope
}
+21 -23
View File
@@ -1,27 +1,29 @@
const operators = require('./operators.js')
const lexical = require('./lexical.js')
const assert = require('../src/util/assert.js')
import Operators from './operators.js'
import * as lexical from './lexical.js'
import assert from './util/assert.js'
function evalExp (exp, scope) {
const operators = Operators(isTruthy)
export 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})$`)
const operatorREs = lexical.operators
let match
for (let i = 0; i < operatorREs.length; i++) {
const operatorRE = operatorREs[i]
const 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)
const l = evalExp(match[1], scope)
const op = operators[match[2].trim()]
const r = evalExp(match[3], scope)
return op(l, r)
}
}
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++) {
const low = evalValue(match[1], scope)
const high = evalValue(match[2], scope)
const range = []
for (let j = low; j <= high; j++) {
range.push(j)
}
return range
@@ -30,7 +32,7 @@ function evalExp (exp, scope) {
return evalValue(exp, scope)
}
function evalValue (str, scope) {
export function evalValue (str, scope) {
str = str && str.trim()
if (!str) return undefined
@@ -43,14 +45,10 @@ function evalValue (str, scope) {
throw new TypeError(`cannot eval '${str}' as value`)
}
function isTruthy (val) {
export function isTruthy (val) {
return !isFalsy(val)
}
function isFalsy (val) {
export function isFalsy (val) {
return val === false || undefined === val || val === null
}
module.exports = {
evalExp, evalValue, isTruthy, isFalsy
}
+22 -22
View File
@@ -1,40 +1,40 @@
const lexical = require('./lexical.js')
const Promise = require('any-promise')
const Syntax = require('./syntax.js')
const assert = require('./util/assert.js')
import {hashCapture} from './lexical.js'
import {create} from './util/underscore.js'
import {evalValue} from './syntax.js'
import assert from './util/assert.js'
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)
const obj = {}
let match
hashCapture.lastIndex = 0
while ((match = hashCapture.exec(markup))) {
const k = match[1]
const v = match[2]
obj[k] = evalValue(v, scope)
}
return obj
}
module.exports = function () {
var tagImpls = {}
export default function () {
let tagImpls = {}
var _tagInstance = {
render: function (scope) {
var obj = hash(this.token.args, scope)
var impl = this.tagImpl
const _tagInstance = {
render: async function (scope) {
const obj = hash(this.token.args, scope)
const impl = this.tagImpl
if (typeof impl.render !== 'function') {
return Promise.resolve('')
return ''
}
return Promise.resolve().then(() => impl.render(scope, obj))
return impl.render(scope, obj)
},
parse: function (token, tokens) {
this.type = 'tag'
this.token = token
this.name = token.name
var tagImpl = tagImpls[this.name]
const tagImpl = tagImpls[this.name]
assert(tagImpl, `tag ${this.name} not found`)
this.tagImpl = Object.create(tagImpl)
this.tagImpl = create(tagImpl)
if (this.tagImpl.parse) {
this.tagImpl.parse(token, tokens)
}
@@ -46,7 +46,7 @@ module.exports = function () {
}
function construct (token, tokens) {
var instance = Object.create(_tagInstance)
const instance = create(_tagInstance)
instance.parse(token, tokens)
return instance
}
+23
View File
@@ -0,0 +1,23 @@
import assert from '../util/assert.js'
import {identifier} from '../lexical.js'
import {create} from '../util/underscore.js'
export default function (liquid, Liquid) {
const re = new RegExp(`(${identifier.source})\\s*=(.*)`)
const {AssignScope} = Liquid.Types
liquid.registerTag('assign', {
parse: function (token) {
const match = token.args.match(re)
assert(match, `illegal token ${token.raw}`)
this.key = match[1]
this.value = match[2]
},
render: function (scope) {
const ctx = create(AssignScope)
ctx[this.key] = liquid.evalValue(this.value, scope)
scope.push(ctx)
return Promise.resolve('')
}
})
}
+32
View File
@@ -0,0 +1,32 @@
import assert from '../util/assert.js'
import {create} from '../util/underscore.js'
import {identifier} from '../lexical.js'
export default function (liquid, Liquid) {
const re = new RegExp(`(${identifier.source})`)
const {CaptureScope} = Liquid.Types
liquid.registerTag('capture', {
parse: function (tagToken, remainTokens) {
const match = tagToken.args.match(re)
assert(match, `${tagToken.args} not valid identifier`)
this.variable = match[1]
this.templates = []
const 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: async function (scope, hash) {
const html = await liquid.renderer.renderTemplates(this.templates, scope)
const ctx = create(CaptureScope)
ctx[this.variable] = html
scope.push(ctx)
}
})
}
+7 -9
View File
@@ -1,6 +1,4 @@
const Liquid = require('..')
module.exports = function (liquid) {
export default function (liquid, Liquid) {
liquid.registerTag('case', {
parse: function (tagToken, remainTokens) {
@@ -8,8 +6,8 @@ module.exports = function (liquid) {
this.cases = []
this.elseTemplates = []
var p = []
var stream = liquid.parser.parseStream(remainTokens)
let p = []
const stream = liquid.parser.parseStream(remainTokens)
.on('tag:when', token => {
this.cases.push({
val: token.args,
@@ -27,10 +25,10 @@ module.exports = function (liquid) {
},
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)
for (let i = 0; i < this.cases.length; i++) {
const branch = this.cases[i]
const val = Liquid.evalExp(branch.val, scope)
const cond = Liquid.evalExp(this.cond, scope)
if (val === cond) {
return liquid.renderer.renderTemplates(branch.templates, scope)
}
+15
View File
@@ -0,0 +1,15 @@
export default function (liquid) {
liquid.registerTag('comment', {
parse: function (tagToken, remainTokens) {
const 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()
}
})
}
+43
View File
@@ -0,0 +1,43 @@
import assert from '../util/assert.js'
import {value as rValue} from '../lexical.js'
export default function (liquid, Liquid) {
const groupRE = new RegExp(`^(?:(${rValue.source})\\s*:\\s*)?(.*)$`)
const candidatesRE = new RegExp(rValue.source, 'g')
liquid.registerTag('cycle', {
parse: function (tagToken, remainTokens) {
let match = groupRE.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.group = match[1] || ''
const candidates = match[2]
this.candidates = []
while ((match = candidatesRE.exec(candidates))) {
this.candidates.push(match[0])
}
assert(this.candidates.length, `empty candidates: ${tagToken.raw}`)
},
render: function (scope, hash) {
const group = Liquid.evalValue(this.group, scope)
const fingerprint = `cycle:${group}:` + this.candidates.join(',')
const groups = scope.opts.groups = scope.opts.groups || {}
let idx = groups[fingerprint]
if (idx === undefined) {
idx = groups[fingerprint] = 0
}
const candidate = this.candidates[idx]
idx = (idx + 1) % this.candidates.length
groups[fingerprint] = idx
return Liquid.evalValue(candidate, scope)
}
})
}
+32
View File
@@ -0,0 +1,32 @@
import {create} from '../util/underscore.js'
import assert from '../util/assert.js'
import {identifier} from '../lexical.js'
export default function (liquid, Liquid) {
const {CaptureScope, AssignScope, DecrementScope} = Liquid.Types
liquid.registerTag('decrement', {
parse: function (token) {
const match = token.args.match(identifier)
assert(match, `illegal identifier ${token.args}`)
this.variable = match[0]
},
render: function (scope, hash) {
let context = scope.findContextFor(
this.variable,
ctx => {
const proto = Object.getPrototypeOf(ctx)
return proto !== CaptureScope && proto !== AssignScope
}
)
if (!context) {
context = create(DecrementScope)
scope.unshift(context)
}
if (typeof context[this.variable] !== 'number') {
context[this.variable] = 0
}
return --context[this.variable]
}
})
}
+93
View File
@@ -0,0 +1,93 @@
import {mapSeries} from '../util/promise.js'
import {isString, isObject, isArray} from '../util/underscore.js'
import assert from '../util/assert.js'
import {identifier, value, hash} from '../lexical.js'
export default function (liquid, Liquid) {
const RenderBreakError = Liquid.Types.RenderBreakError
const re = new RegExp(`^(${identifier.source})\\s+in\\s+` +
`(${value.source})` +
`(?:\\s+${hash.source})*` +
`(?:\\s+(reversed))?` +
`(?:\\s+${hash.source})*$`)
liquid.registerTag('for', {parse, render})
function parse (tagToken, remainTokens) {
const 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 = []
let p
const 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()
}
async function render (scope, hash) {
let collection = Liquid.evalExp(this.collection, scope)
if (!isArray(collection)) {
if (isString(collection) && collection.length > 0) {
collection = [collection]
} else if (isObject(collection)) {
collection = Object.keys(collection).map((key) => [key, collection[key]])
}
}
if (!isArray(collection) || !collection.length) {
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
const offset = hash.offset || 0
const limit = (hash.limit === undefined) ? collection.length : hash.limit
collection = collection.slice(offset, offset + limit)
if (this.reversed) collection.reverse()
const contexts = collection.map((item, i) => {
const 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
})
let html = ''
let finished = false
await mapSeries(contexts, async context => {
if (finished) return
scope.push(context)
try {
html += await liquid.renderer.renderTemplates(this.templates, scope)
} catch (e) {
if (e instanceof RenderBreakError) {
html += e.resolvedHTML
if (e.message === 'break') {
finished = true
}
} else throw e
}
scope.pop(context)
})
return html
}
}
+5 -8
View File
@@ -1,14 +1,12 @@
const Liquid = require('..')
module.exports = function (liquid) {
export default function (liquid, Liquid) {
liquid.registerTag('if', {
parse: function (tagToken, remainTokens) {
this.branches = []
this.elseTemplates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
let p
const stream = liquid.parser.parseStream(remainTokens)
.on('start', () => this.branches.push({
cond: tagToken.args,
templates: (p = [])
@@ -30,9 +28,8 @@ module.exports = function (liquid) {
},
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)
for (const branch of this.branches) {
const cond = Liquid.evalExp(branch.cond, scope)
if (Liquid.isTruthy(cond)) {
return liquid.renderer.renderTemplates(branch.templates, scope)
}
+57
View File
@@ -0,0 +1,57 @@
import assert from '../util/assert.js'
import {value, quotedLine} from '../lexical.js'
const staticFileRE = /[^\s,]+/
export default function (liquid, Liquid) {
const withRE = new RegExp(`with\\s+(${value.source})`)
liquid.registerTag('include', {
parse: function (token) {
let match = staticFileRE.exec(token.args)
if (match) {
this.staticValue = match[0]
}
match = value.exec(token.args)
if (match) {
this.value = match[0]
}
match = withRE.exec(token.args)
if (match) {
this.with = match[1]
}
},
render: async function (scope, hash) {
let filepath
if (scope.opts.dynamicPartials) {
if (quotedLine.exec(this.value)) {
const template = this.value.slice(1, -1)
filepath = await liquid.parseAndRender(template, scope.getAll(), scope.opts)
} else {
filepath = Liquid.evalValue(this.value, scope)
}
} else {
filepath = this.staticValue
}
assert(filepath, `cannot include with empty filename`)
const originBlocks = scope.opts.blocks
const originBlockMode = scope.opts.blockMode
scope.opts.blocks = {}
scope.opts.blockMode = 'output'
if (this.with) {
hash[filepath] = Liquid.evalValue(this.with, scope)
}
const templates = await liquid.getTemplate(filepath, scope.opts.root)
scope.push(hash)
const html = await liquid.renderer.renderTemplates(templates, scope)
scope.pop(hash)
scope.opts.blocks = originBlocks
scope.opts.blockMode = originBlockMode
return html
}
})
}
+34
View File
@@ -0,0 +1,34 @@
import assert from '../util/assert.js'
import {create} from '../util/underscore.js'
import {identifier} from '../lexical.js'
export default function (liquid, Liquid) {
const {CaptureScope, AssignScope, IncrementScope} = Liquid.Types
liquid.registerTag('increment', {
parse: function (token) {
const match = token.args.match(identifier)
assert(match, `illegal identifier ${token.args}`)
this.variable = match[0]
},
render: function (scope, hash) {
let context = scope.findContextFor(
this.variable,
ctx => {
const proto = Object.getPrototypeOf(ctx)
return proto !== CaptureScope && proto !== AssignScope
}
)
if (!context) {
context = create(IncrementScope)
scope.unshift(context)
}
if (typeof context[this.variable] !== 'number') {
context[this.variable] = 0
}
const val = context[this.variable]
context[this.variable]++
return val
}
})
}
+31
View File
@@ -0,0 +1,31 @@
import For from './for.js'
import Assign from './assign.js'
import Capture from './capture.js'
import Case from './case.js'
import Comment from './comment.js'
import Include from './include.js'
import Decrement from './decrement.js'
import Cycle from './cycle.js'
import If from './if.js'
import Increment from './increment.js'
import Layout from './layout.js'
import Raw from './raw.js'
import Tablerow from './tablerow.js'
import Unless from './unless.js'
export default function (engine, Liquid) {
Assign(engine, Liquid)
Capture(engine, Liquid)
Case(engine, Liquid)
Comment(engine, Liquid)
Cycle(engine, Liquid)
Decrement(engine, Liquid)
For(engine, Liquid)
If(engine, Liquid)
Include(engine, Liquid)
Increment(engine, Liquid)
Layout(engine, Liquid)
Raw(engine, Liquid)
Tablerow(engine, Liquid)
Unless(engine, Liquid)
}
+75
View File
@@ -0,0 +1,75 @@
import assert from '../util/assert.js'
import {value as rValue} from '../lexical.js'
/*
* blockMode:
* * "store": store rendered html into blocks
* * "output": output rendered html
*/
export default function (liquid, Liquid) {
const staticFileRE = /\S+/
liquid.registerTag('layout', {
parse: function (token, remainTokens) {
let match = staticFileRE.exec(token.args)
if (match) {
this.staticLayout = match[0]
}
match = rValue.exec(token.args)
if (match) {
this.layout = match[0]
}
this.tpls = liquid.parser.parse(remainTokens)
},
render: async function (scope, hash) {
const layout = scope.opts.dynamicPartials
? Liquid.evalValue(this.layout, scope)
: this.staticLayout
assert(layout, `cannot apply layout with empty filename`)
// render the remaining tokens immediately
scope.opts.blockMode = 'store'
const html = await liquid.renderer.renderTemplates(this.tpls, scope)
if (scope.opts.blocks[''] === undefined) {
scope.opts.blocks[''] = html
}
const templates = await liquid.getTemplate(layout, scope.opts.root)
scope.push(hash)
scope.opts.blockMode = 'output'
const partial = await liquid.renderer.renderTemplates(templates, scope)
scope.pop(hash)
return partial
}
})
liquid.registerTag('block', {
parse: function (token, remainTokens) {
const match = /\w+/.exec(token.args)
this.block = match ? match[0] : ''
this.tpls = []
const 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: async function (scope) {
const childDefined = scope.opts.blocks[this.block]
const html = childDefined !== undefined
? childDefined
: await liquid.renderer.renderTemplates(this.tpls, scope)
if (scope.opts.blockMode === 'store') {
scope.opts.blocks[this.block] = html
return ''
}
return html
}
})
}
+21
View File
@@ -0,0 +1,21 @@
export default function (liquid) {
liquid.registerTag('raw', {
parse: function (tagToken, remainTokens) {
this.tokens = []
const stream = liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
if (token.name === 'endraw') stream.stop()
else this.tokens.push(token)
})
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
return this.tokens.map(token => token.raw).join('')
}
})
}
+70
View File
@@ -0,0 +1,70 @@
import {mapSeries} from '../util/promise.js'
import assert from '../util/assert.js'
import {identifier, value, hash} from '../lexical.js'
export default function (liquid, Liquid) {
const re = new RegExp(`^(${identifier.source})\\s+in\\s+` +
`(${value.source})` +
`(?:\\s+${hash.source})*$`)
liquid.registerTag('tablerow', {
parse: function (tagToken, remainTokens) {
const match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1]
this.collection = match[2]
this.templates = []
let p
const 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()
},
render: async function (scope, hash) {
let collection = Liquid.evalExp(this.collection, scope) || []
const offset = hash.offset || 0
const limit = (hash.limit === undefined) ? collection.length : hash.limit
collection = collection.slice(offset, offset + limit)
const cols = hash.cols || collection.length
const contexts = collection.map((item, i) => {
const ctx = {}
ctx[this.variable] = item
return ctx
})
let row
let html = ''
await mapSeries(contexts, async (context, idx) => {
row = Math.floor(idx / cols) + 1
const col = (idx % cols) + 1
if (col === 1) {
if (row !== 1) {
html += '</tr>'
}
html += `<tr class="row${row}">`
}
html += `<td class="col${col}">`
scope.push(context)
html += await liquid.renderer.renderTemplates(this.templates, scope)
html += '</td>'
scope.pop(context)
return html
})
if (row > 0) {
html += '</tr>'
}
return html
}
})
}
+29
View File
@@ -0,0 +1,29 @@
export default function (liquid, Liquid) {
liquid.registerTag('unless', {
parse: function (tagToken, remainTokens) {
this.templates = []
this.elseTemplates = []
let p
const 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()
},
render: function (scope, hash) {
const cond = Liquid.evalExp(this.cond, scope)
return Liquid.isFalsy(cond)
? liquid.renderer.renderTemplates(this.templates, scope)
: liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
})
}
+52
View File
@@ -0,0 +1,52 @@
import {last, isArray} from './util/underscore'
function domResolve (root, path) {
const base = document.createElement('base')
base.href = root
const head = document.getElementsByTagName('head')[0]
head.insertBefore(base, head.firstChild)
const a = document.createElement('a')
a.href = path
const resolved = a.href
head.removeChild(base)
return resolved
}
export function resolve (filepath, root, options) {
root = root || options.root
if (isArray(root)) {
root = root[0]
}
if (root.length && last(root) !== '/') {
root += '/'
}
const url = domResolve(root, filepath)
return url.replace(/^(\w+:\/\/[^/]+)(\/[^?]+)/, (str, origin, path) => {
const last = path.split('/').pop()
if (/\.\w+$/.test(last)) {
return str
}
return origin + path + options.extname
})
}
export async function read (url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText)
} else {
reject(new Error(xhr.statusText))
}
}
xhr.onerror = () => {
reject(new Error('An error occurred whilst receiving the response.'))
}
xhr.open('GET', url)
xhr.send()
})
}
+29
View File
@@ -0,0 +1,29 @@
import * as _ from './util/underscore.js'
import path from 'path'
import {anySeries} from './util/promise.js'
import fs from 'fs'
const statFileAsync = _.promisify(fs.stat)
const readFileAsync = _.promisify(fs.readFile)
export async function resolve (filepath, root, options) {
if (!path.extname(filepath)) {
filepath += options.extname
}
root = options.root.concat(root || [])
root = _.uniq(root)
const paths = root.map(root => path.resolve(root, filepath))
return anySeries(paths, async path => {
try {
await statFileAsync(path)
return path
} catch (e) {
e.message = `${e.code}: Failed to lookup ${filepath} in: ${root}`
throw e
}
})
}
export async function read (filepath) {
return readFileAsync(filepath, 'utf8')
}
+73 -79
View File
@@ -1,96 +1,90 @@
const lexical = require('./lexical.js')
const TokenizationError = require('./util/error.js').TokenizationError
const _ = require('./util/underscore.js')
const assert = require('../src/util/assert.js')
import * as lexical from './lexical.js'
import {TokenizationError} from './util/error.js'
import * as _ from './util/underscore.js'
import assert from './util/assert.js'
import whiteSpaceCtrl from './whitespace-ctrl.js'
function parse (html, filepath, options) {
assert(_.isString(html), 'illegal input type')
export {default as whiteSpaceCtrl} from './whitespace-ctrl.js'
html = whiteSpaceCtrl(html, options)
export function parse (input, file, options) {
assert(_.isString(input), 'illegal input')
var tokens = []
var syntax = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
var result, htmlFragment, token
var lastMatchEnd = 0
var lastMatchBegin = -1
var parsedLinesCount = 0
const rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
let currIndent = 0
const lineNumber = LineNumber(input)
let lastMatchEnd = 0
const tokens = []
while ((result = syntax.exec(html)) !== null) {
// passed html fragments
if (result.index > lastMatchEnd) {
htmlFragment = html.slice(lastMatchEnd, result.index)
tokens.push({
type: 'html',
raw: htmlFragment,
value: htmlFragment
})
for (let match; (match = rLiquid.exec(input)); lastMatchEnd = rLiquid.lastIndex) {
if (match.index > lastMatchEnd) {
tokens.push(parseHTMLToken(lastMatchEnd, match.index))
}
if (result[1]) {
// tag appeared
token = factory('tag', 1, result)
tokens.push(match[1]
? parseTagToken(match[1], match[2].trim(), match.index)
: parseValueToken(match[3], match[4].trim(), match.index))
}
if (input.length > lastMatchEnd) {
tokens.push(parseHTMLToken(lastMatchEnd, input.length))
}
whiteSpaceCtrl(tokens, options)
return tokens
var match = token.value.match(lexical.tagLine)
if (!match) {
throw new TokenizationError(`illegal tag syntax`, token)
}
token.name = match[1]
token.args = match[2]
// get last line indentation
var lineStart = (htmlFragment || '').split('\n')
token.indent = lineStart[lineStart.length - 1].length
tokens.push(token)
} else {
// output
token = factory('output', 3, result)
tokens.push(token)
function parseTagToken (raw, value, pos) {
const match = value.match(lexical.tagLine)
const token = {
type: 'tag',
indent: currIndent,
line: lineNumber.get(pos),
trim_left: raw.slice(0, 3) === '{%-',
trim_right: raw.slice(-3) === '-%}',
raw,
value,
input,
file
}
lastMatchEnd = syntax.lastIndex
if (!match) {
throw new TokenizationError(`illegal tag syntax`, token)
}
token.name = match[1]
token.args = match[2]
return token
}
// remaining html
if (html.length > lastMatchEnd) {
htmlFragment = html.slice(lastMatchEnd, html.length)
tokens.push({
function parseValueToken (raw, value, pos) {
return {
type: 'value',
line: lineNumber.get(pos),
trim_left: raw.slice(0, 3) === '{{-',
trim_right: raw.slice(-3) === '-}}',
raw,
value,
input,
file
}
}
function parseHTMLToken (begin, end) {
const htmlFragment = input.slice(begin, end)
currIndent = _.last((htmlFragment).split('\n')).length
return {
type: 'html',
raw: htmlFragment,
value: htmlFragment
})
}
return tokens
function factory (type, offset, match) {
return {
type: type,
raw: match[offset],
value: match[offset + 1].trim(),
line: getLineNum(match),
input: html,
file: filepath
}
}
function getLineNum (match) {
var lines = match.input.slice(lastMatchBegin + 1, match.index).split('\n')
parsedLinesCount += lines.length - 1
lastMatchBegin = match.index
return parsedLinesCount + 1
}
}
function whiteSpaceCtrl (html, options) {
options = options || {}
if (options.trim_left) {
html = html.replace(/({[{%])-?/g, '$1-')
}
if (options.trim_right) {
html = html.replace(/-?([%}]})/g, '-$1')
}
var rLeft = options.greedy ? /\s+({[{%]-)/g : /[\t\r ]*({[{%]-)/g
var rRight = options.greedy ? /(-[%}]})\s+/g : /(-[%}]})[\t\r ]*\n?/g
return html.replace(rLeft, '$1').replace(rRight, '$1')
}
function LineNumber (html) {
let parsedLinesCount = 0
let lastMatchBegin = -1
exports.parse = parse
exports.whiteSpaceCtrl = whiteSpaceCtrl
return {
get: function (pos) {
const lines = html.slice(lastMatchBegin + 1, pos).split('\n')
parsedLinesCount += lines.length - 1
lastMatchBegin = pos
return parsedLinesCount + 1
}
}
}
+2 -4
View File
@@ -1,10 +1,8 @@
const AssertionError = require('./error.js').AssertionError
import {AssertionError} from './error.js'
function assert (predicate, message) {
export default function (predicate, message) {
if (!predicate) {
message = message || `expect ${predicate} to be true`
throw new AssertionError(message)
}
}
module.exports = assert
+27 -33
View File
@@ -1,4 +1,4 @@
const _ = require('./underscore.js')
import * as _ from './underscore.js'
function initError () {
this.name = this.constructor.name
@@ -7,34 +7,36 @@ function initError () {
}
}
function initLiquidError (message, token) {
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(message, token)
this.stack = context + '\n' + (this.stack || this.message)
const 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, token)
export function TokenizationError (message, token) {
initLiquidError.call(this, {message: message}, token)
}
TokenizationError.prototype = Object.create(Error.prototype)
TokenizationError.prototype = _.create(Error.prototype)
TokenizationError.prototype.constructor = TokenizationError
function ParseError (e, token) {
export function ParseError (e, token) {
_.assign(this, e)
this.originalError = e
initLiquidError.call(this, e.message, token)
initLiquidError.call(this, e, token)
}
ParseError.prototype = Object.create(Error.prototype)
ParseError.prototype = _.create(Error.prototype)
ParseError.prototype.constructor = ParseError
function RenderError (e, tpl) {
export function RenderError (e, tpl) {
// return the original render error
if (e instanceof RenderError) {
return e
@@ -42,31 +44,31 @@ function RenderError (e, tpl) {
_.assign(this, e)
this.originalError = e
initLiquidError.call(this, e.message, tpl.token)
initLiquidError.call(this, e, tpl.token)
}
RenderError.prototype = Object.create(Error.prototype)
RenderError.prototype = _.create(Error.prototype)
RenderError.prototype.constructor = RenderError
function RenderBreakError (message) {
export function RenderBreakError (message) {
initError.call(this)
this.message = message + ''
}
RenderBreakError.prototype = Object.create(Error.prototype)
RenderBreakError.prototype = _.create(Error.prototype)
RenderBreakError.prototype.constructor = RenderBreakError
function AssertionError (message) {
export function AssertionError (message) {
initError.call(this)
this.message = message + ''
}
AssertionError.prototype = Object.create(Error.prototype)
AssertionError.prototype = _.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)
const lines = input.split('\n')
const begin = Math.max(line - 2, 1)
const end = Math.min(line + 3, lines.length)
var context = _
const context = _
.range(begin, end + 1)
.map(l => [
(l === line) ? '>> ' : ' ',
@@ -80,9 +82,9 @@ function mkContext (input, line) {
}
function align (n, max) {
var length = (max + '').length
var str = n + ''
var blank = Array(length - str.length).join(' ')
const length = (max + '').length
const str = n + ''
const blank = Array(length - str.length).join(' ')
return blank + str
}
@@ -96,11 +98,3 @@ function mkMessage (msg, token) {
}
return msg
}
module.exports = {
TokenizationError,
ParseError,
RenderBreakError,
AssertionError,
RenderError
}
-20
View File
@@ -1,20 +0,0 @@
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 statFileAsync (path) {
return new Promise(function (resolve, reject) {
fs.stat(path, (err, stat) => err ? reject(err) : resolve(stat))
})
};
module.exports = {
readFileAsync,
statFileAsync
}
+5 -10
View File
@@ -1,13 +1,11 @@
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).
*/
function anySeries (iterable, iteratee) {
var ret = Promise.reject(new Error('init'))
export function anySeries (iterable, iteratee) {
let ret = Promise.reject(new Error('init'))
iterable.forEach(function (item, idx) {
ret = ret.catch(e => iteratee(item, idx, iterable))
})
@@ -20,9 +18,9 @@ function anySeries (iterable, iteratee) {
* @param {Array} iteratee returns a new promise.
* The iteratee is invoked with three arguments: (value, index, iterable).
*/
function mapSeries (iterable, iteratee) {
var ret = Promise.resolve('init')
var result = []
export function mapSeries (iterable, iteratee) {
let ret = Promise.resolve('init')
const result = []
iterable.forEach(function (item, idx) {
ret = ret
.then(() => iteratee(item, idx, iterable))
@@ -30,6 +28,3 @@ function mapSeries (iterable, iteratee) {
})
return ret.then(() => result)
}
exports.anySeries = anySeries
exports.mapSeries = mapSeries
+31 -33
View File
@@ -1,32 +1,33 @@
var monthNames = [
const monthNames = [
'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'
]
var dayNames = [
const dayNames = [
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
]
var dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
var suffixes = {
const monthNamesShort = monthNames.map(abbr)
const dayNamesShort = dayNames.map(abbr)
const suffixes = {
1: 'st',
2: 'nd',
3: 'rd',
'default': 'th'
}
function abbr (str) {
return str.slice(0, 3)
}
// prototype extensions
var _date = {
const _date = {
daysInMonth: function (d) {
var feb = _date.isLeapYear(d) ? 29 : 28
const 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) {
let num = 0
for (let i = 0; i < d.getMonth(); ++i) {
num += _date.daysInMonth(d)[i]
}
return num + d.getDate()
@@ -36,21 +37,21 @@ var _date = {
// 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())
const 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)
const jan1 = new Date(d.getFullYear(), 0, 1)
const then = (7 - jan1.getDay() + startDay)
return _number.pad(Math.floor((now - then) / 7) + 1, 2)
},
isLeapYear: function (d) {
var year = d.getFullYear()
const 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))
const str = d.getDate().toString()
const index = parseInt(str.slice(-1))
return suffixes[index] || suffixes['default']
},
@@ -59,11 +60,11 @@ var _date = {
}
}
var _number = {
const _number = {
pad: function (value, size, ch) {
if (!ch) ch = '0'
var result = value.toString()
var pad = size - result.length
let result = value.toString()
let pad = size - result.length
while (pad-- > 0) {
result = ch + result
@@ -73,7 +74,7 @@ var _number = {
}
}
var formatCodes = {
const formatCodes = {
a: function (d) {
return dayNamesShort[d.getDay()]
},
@@ -162,8 +163,7 @@ var formatCodes = {
return d.getFullYear()
},
z: function (d) {
var tz = d.getTimezoneOffset() / 60 * 100
console.log('tz', tz)
const tz = d.getTimezoneOffset() / 60 * 100
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4)
},
'%': function () {
@@ -173,13 +173,13 @@ var formatCodes = {
formatCodes.h = formatCodes.b
formatCodes.N = formatCodes.L
var strftime = function (d, format) {
var output = ''
var remaining = format
export default function (d, format) {
let output = ''
let remaining = format
while (true) {
var r = /%./g
var results = r.exec(remaining)
const r = /%./g
const results = r.exec(remaining)
// No more format codes. Add the remaining text and return
if (!results) {
@@ -191,10 +191,8 @@ var strftime = function (d, format) {
remaining = remaining.slice(r.lastIndex)
// Add the format code
var ch = results[0].charAt(1)
var func = formatCodes[ch]
const ch = results[0].charAt(1)
const func = formatCodes[ch]
output += func ? func.call(this, d) : '%' + ch
}
}
module.exports = strftime
+63 -49
View File
@@ -5,21 +5,61 @@ const toStr = Object.prototype.toString
* @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'
export function isString (value) {
return toStr.call(value) === '[object String]'
}
function isNil (value) {
export function promisify (fn) {
return function () {
return new Promise((resolve, reject) => {
fn(...arguments, (err, result) => {
err ? reject(err) : resolve(result)
})
})
}
}
export function stringify (value) {
if (isNil(value)) {
return String(value)
}
if (typeof value.to_liquid === 'function') {
return stringify(value.to_liquid())
}
if (typeof value.toLiquid === 'function') {
return stringify(value.toLiquid())
}
if (isString(value) || value instanceof RegExp || value instanceof Date) {
return value.toString()
}
const cache = []
return JSON.stringify(value, (key, value) => {
if (isObject(value)) {
if (cache.indexOf(value) !== -1) {
return
}
cache.push(value)
}
return value
})
}
export function create (proto) {
return Object.create(proto)
}
export function isNil (value) {
return value === null || value === undefined
}
function isArray (value) {
export function isArray (value) {
// be compatible with IE 8
return toStr.call(value) === '[object Array]'
}
function isError (value) {
var signature = Object.prototype.toString.call(value)
export function isError (value) {
const signature = toStr.call(value)
// [object XXXError]
return signature.substr(-6, 5) === 'Error' ||
(typeof value.message === 'string' && typeof value.name === 'string')
@@ -33,9 +73,9 @@ function isError (value) {
* @param {Function} iteratee The function invoked per iteration.
* @return {Object} Returns object.
*/
function forOwn (object, iteratee) {
export function forOwn (object, iteratee) {
object = object || {}
for (var k in object) {
for (const k in object) {
if (object.hasOwnProperty(k)) {
if (iteratee(object[k], k, object) === false) break
}
@@ -54,33 +94,21 @@ function forOwn (object, iteratee) {
* @param {...Object} sources The source objects.
* @return {Object} Returns object.
*/
function assign (object) {
export function assign (object) {
object = isObject(object) ? object : {}
var srcs = Array.prototype.slice.call(arguments, 1)
srcs.forEach(function (src) {
_assignBinary(object, src)
})
const srcs = Array.prototype.slice.call(arguments, 1)
srcs.forEach((src) => Object.assign(object, src))
return object
}
function _assignBinary (dst, src) {
forOwn(src, function (v, k) {
dst[k] = v
})
return dst
export function last (arr) {
return arr[arr.length - 1]
}
function echo (prefix) {
return v => {
console.log('[' + prefix + ']', v)
return v
}
}
function uniq (arr) {
var u = {}
var a = []
for (var i = 0, l = arr.length; i < l; ++i) {
export function uniq (arr) {
const u = {}
const a = []
for (let i = 0, l = arr.length; i < l; ++i) {
if (u.hasOwnProperty(arr[i])) {
continue
}
@@ -96,9 +124,9 @@ function uniq (arr) {
* @param {any} value The value to check.
* @return {Boolean} Returns true if value is an object, else false.
*/
function isObject (value) {
var type = typeof value
return value != null && (type === 'object' || type === 'function')
export function isObject (value) {
const type = typeof value
return value !== null && (type === 'object' || type === 'function')
}
/*
@@ -109,30 +137,16 @@ function isObject (value) {
* 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) {
export 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) {
const arr = []
for (let i = start; i < stop; i += step) {
arr.push(i)
}
return arr
}
exports.isString = isString
exports.isObject = isObject
exports.isArray = isArray
exports.isNil = isNil
exports.isError = isError
exports.range = range
exports.forOwn = forOwn
exports.assign = assign
exports.uniq = uniq
exports.echo = echo
+45
View File
@@ -0,0 +1,45 @@
import {assign} from './util/underscore.js'
export default function whiteSpaceCtrl (tokens, options) {
options = assign({ greedy: true }, options)
let 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
const rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
token.value = token.value.replace(rLeft, '')
}
function trimRight (token, greedy) {
if (!token || token.type !== 'html') return
const rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
token.value = token.value.replace(rRight, '')
}
-20
View File
@@ -1,20 +0,0 @@
const Liquid = require('..')
const lexical = Liquid.lexical
const Promise = require('any-promise')
const re = new RegExp(`(${lexical.identifier.source})\\s*=(.*)`)
const assert = require('../src/util/assert.js')
module.exports = function (liquid) {
liquid.registerTag('assign', {
parse: function (token) {
var match = token.args.match(re)
assert(match, `illegal token ${token.raw}`)
this.key = match[1]
this.value = match[2]
},
render: function (scope) {
scope.set(this.key, liquid.evalOutput(this.value, scope))
return Promise.resolve('')
}
})
}
-32
View File
@@ -1,32 +0,0 @@
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) {
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 = [];
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);
});
}
});
};
-17
View File
@@ -1,17 +0,0 @@
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();
}
});
};
-44
View File
@@ -1,44 +0,0 @@
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');
module.exports = function(liquid) {
liquid.registerTag('cycle', {
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.candidates = [];
while(match = candidatesRE.exec(candidates)){
this.candidates.push(match[0]);
}
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(',');
var register = scope.get('liquid');
var idx = register[fingerprint];
if(idx === undefined){
idx = register[fingerprint] = 0;
}
var candidate = this.candidates[idx];
idx = (idx + 1) % this.candidates.length;
register[fingerprint] = idx;
return Promise.resolve(Liquid.evalValue(candidate, scope));
}
});
};
-20
View File
@@ -1,20 +0,0 @@
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);
}
});
};
-97
View File
@@ -1,97 +0,0 @@
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+${lexical.hash.source})*$`)
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]
this.templates = []
this.elseTemplates = []
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()
},
render: function (scope, hash) {
var collection = Liquid.evalExp(this.collection, scope)
if (!Array.isArray(collection)) {
if (_.isString(collection) && collection.length > 0) {
collection = [collection]
} else if (_.isObject(collection)) {
collection = Object.keys(collection)
}
}
if (!Array.isArray(collection) || !collection.length) {
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
var length = collection.length
var offset = hash.offset || 0
var limit = (hash.limit === undefined) ? collection.length : hash.limit
collection = collection.slice(offset, offset + limit)
if (this.reversed) collection.reverse()
var contexts = collection.map((item, i) => {
var ctx = {}
ctx[this.variable] = item
ctx.forloop = {
first: i === 0,
index: i + 1,
index0: i,
last: i === length - 1,
length: length,
rindex: length - i,
rindex0: length - i - 1
}
return ctx
})
var html = ''
return mapSeries(contexts, (context) => {
return Promise.resolve()
.then(() => scope.push(context))
.then(() => liquid.renderer.renderTemplates(this.templates, scope))
.then(partial => (html += partial))
.catch(e => {
if (e instanceof RenderBreakError) {
html += e.resolvedHTML
if (e.message === 'continue') return
}
throw e
})
.then(() => scope.pop())
}).catch((e) => {
if (e instanceof RenderBreakError && e.message === 'break') {
return
}
throw e
}).then(() => html)
}
})
}
-42
View File
@@ -1,42 +0,0 @@
const Liquid = require('..');
const lexical = Liquid.lexical;
const withRE = new RegExp(`with\\s+(${lexical.value.source})`);
const assert = require('../src/util/assert.js');
module.exports = function(liquid) {
liquid.registerTag('include', {
parse: function(token){
var match = lexical.value.exec(token.args);
assert(match, `illegal token ${token.raw}`);
this.value = match[0];
match = withRE.exec(token.args);
if(match){
this.with = match[1];
}
},
render: function(scope, hash) {
var filepath = Liquid.evalValue(this.value, scope);
var register = scope.get('liquid');
var originBlocks = register.blocks;
register.blocks = {};
if(this.with){
hash[filepath] = Liquid.evalValue(this.with, scope);
}
return liquid.getTemplate(filepath, register.root)
.then((templates) => {
scope.push(hash);
return liquid.renderer.renderTemplates(templates, scope);
})
.then((html) => {
scope.pop();
register.blocks = originBlocks;
return html;
});
}
});
};
-20
View File
@@ -1,20 +0,0 @@
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);
}
});
};
-16
View File
@@ -1,16 +0,0 @@
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);
};
-66
View File
@@ -1,66 +0,0 @@
const Liquid = require('..');
const Promise = require('any-promise');
const lexical = Liquid.lexical;
const assert = require('../src/util/assert.js');
module.exports = function(liquid) {
liquid.registerTag('layout', {
parse: function(token, remainTokens){
var match = lexical.value.exec(token.args);
assert(match, `illegal token ${token.raw}`);
this.layout = match[0];
this.tpls = liquid.parser.parse(remainTokens);
},
render: function(scope, hash) {
var layout = Liquid.evalValue(this.layout, scope);
var register = scope.get('liquid');
// render the remaining tokens immediately
return liquid.renderer.renderTemplates(this.tpls, scope)
// now register.blocks contains rendered blocks
.then(() => liquid.getTemplate(layout, register.root))
// push the hash
.then(templates => (scope.push(hash), templates))
// render the parent
.then(templates => liquid.renderer.renderTemplates(templates, scope))
// pop the hash
.then(partial => (scope.pop(), partial));
}
});
liquid.registerTag('block', {
parse: function(token, remainTokens){
var match = /\w+/.exec(token.args);
this.block = match ? match[0] : 'anonymous';
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);
}
}
});
};
-24
View File
@@ -1,24 +0,0 @@
const Promise = require('any-promise')
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)
}
})
}
-84
View File
@@ -1,84 +0,0 @@
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})*$`)
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]
this.templates = []
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()
},
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 cols = hash.cols
var row
var col
if (!cols) throw new Error(`illegal cols: ${cols}`)
// build array of arguments to pass to sequential promises...
collection = collection.slice(offset, offset + limit)
var contexts = []
collection.some((item, i) => {
var ctx = {}
ctx[this.variable] = item
contexts.push(ctx)
})
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}">`
}
html += `<td class="col${col}">`
scope.push(context)
return liquid.renderer
.renderTemplates(this.templates, scope)
.then((partial) => {
scope.pop(context)
html += partial
html += '</td>'
return html
})
})
.then(() => {
if (row > 0) {
html += '</tr>'
}
html += '</table>'
return html
})
}
})
}
-30
View File
@@ -1,30 +0,0 @@
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`);
});
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);
}
});
};
+6
View File
@@ -0,0 +1,6 @@
{
"rules": {
"no-var": 0,
"prefer-const": 0
}
}
+10 -7
View File
@@ -1,9 +1,12 @@
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 mock = require('mock-fs')
const Liquid = require('../../dist/liquid.common.js')
const chaiAsPromised = require('chai-as-promised')
const expect = chai.expect
chai.use(chaiAsPromised)
describe('engine#express()', function () {
var app, engine
@@ -36,11 +39,11 @@ describe('engine#express()', function () {
.expect(200, done)
})
it('should pass error when file not found', function (done) {
var view = {
const view = {
root: []
}
var file = '/not-exist.html'
var ctx = {}
const file = '/not-exist.html'
const ctx = {}
engine.express().call(view, file, ctx, function (err) {
try {
expect(err.code).to.equal('ENOENT')
@@ -82,7 +85,7 @@ describe('engine#express()', function () {
.expect(200, done)
})
it('should respect express views (Undefined) when lookup', function (done) {
var files = {}
const files = {}
files[process.cwd() + '/views/include.html'] = '{% include file %}'
files[process.cwd() + '/views/bar.html'] = 'bar'
mock(files)
+59
View File
@@ -0,0 +1,59 @@
var chai = require('chai')
var Liquid = require('../..')
var expect = chai.expect
chai.use(require('chai-as-promised'))
describe('.parseAndRender()', function () {
var engine, strictEngine
beforeEach(function () {
engine = Liquid()
strictEngine = Liquid({
strict_filters: true
})
})
it('should value object', function () {
var ctx = { obj: {foo: 'bar'} }
return expect(engine.parseAndRender('{{obj}}', ctx)).to.eventually.equal('{"foo":"bar"}')
})
it('should value array', function () {
var ctx = { arr: [-2, 'a'] }
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', {})).to.eventually.equal('foobar')
})
it('should render as null when filter undefined', function () {
return expect(engine.parseAndRender('{{"foo" | filter1}}', {})).to.eventually.equal('foo')
})
it('should throw upon undefined filter when strict_filters set', function () {
return expect(strictEngine.parseAndRender('{{"foo" | filter1}}', {})).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 ctx = {obj: {foo: 'bar'}}
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 ctx = {names: ['alice', 'bob']}
var template = engine.parse('<p>{{names | join: ","}}</p>')
return expect(engine.render(template, ctx)).to.eventually.equal('<p>alice,bob</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')
})
})
+78
View File
@@ -0,0 +1,78 @@
var chai = require('chai')
var mock = require('mock-fs')
var Liquid = require('../..')
var expect = chai.expect
chai.use(require('chai-as-promised'))
describe('#renderFile()', function () {
var engine
beforeEach(function () {
engine = Liquid({
root: '/root/',
extname: '.html'
})
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()
})
it('should render file', function () {
return expect(engine.renderFile('/root/files/foo.html', {}))
.to.eventually.equal('foo')
})
it('should find files without extname', function () {
var engine = Liquid({root: '/root'})
return expect(engine.renderFile('/root/files/bar', {}))
.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 expect(engine.renderFile('/root/files/name.html', {name: 'harttle'}))
.to.eventually.equal('My name is harttle.')
})
it('should use default extname', function () {
return expect(engine.renderFile('files/name', {name: 'harttle'})).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/)
})
})
+448
View File
@@ -0,0 +1,448 @@
const chai = require('chai')
const Liquid = require('../..')
const liquid = new Liquid()
const expect = chai.expect
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)
))
})
+161
View File
@@ -0,0 +1,161 @@
var Liquid = require('../../dist/liquid.js')
var sinon = require('sinon')
var chai = require('chai')
var expect = chai.expect
chai.use(require('chai-as-promised'))
describe('xhr', () => {
if (process.version.match(/^v(\d+)/)[1] < 8) {
console.info('jsdom not supported, skipping xhr...')
return
}
var JSDOM = require('jsdom').JSDOM
var server, engine
beforeEach(() => {
server = sinon.createFakeServer()
server.autoRespond = true
server.respondWith('GET', 'https://example.com/views/hello.html',
[200, {'Content-Type': 'text/plain'}, 'hello {{name}}'])
var 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')
.then(() => done('should not be resolved'))
.catch(function (e) {
expect(e.message).to.equal('An error occurred whilst receiving the response.')
done()
})
global.XMLHttpRequest.onCreate = function (request) {
setTimeout(() => request.error())
}
})
})
describe('#renderFile() with root specified', () => {
it('should support undefined root', () => {
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 empty root', () => {
engine = Liquid({
root: '',
extname: '.html'
})
server.respondWith('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'))
})
})
})
-57
View File
@@ -1,57 +0,0 @@
const chai = require('chai')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
const expect = chai.expect
chai.use(sinonChai)
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')
})
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"')
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 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 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)
})
})
-232
View File
@@ -1,232 +0,0 @@
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('Liquid', function () {
it('should ignore invalid root option', function () {
var liquid = Liquid({ root: /regex/ })
expect(liquid.options.root).to.deep.equal([])
})
})
describe('{{output}}', function () {
it('should output object', function () {
return expect(engine.parseAndRender('{{obj}}', ctx)).to.eventually.equal('{"foo":"bar"}')
})
it('should output array', function () {
return expect(engine.parseAndRender('{{arr}}', ctx)).to.eventually.equal('[-2,"a"]')
})
it('should output undefined to empty', function () {
return expect(engine.parseAndRender('foo{{zzz}}bar', ctx)).to.eventually.equal('foobar')
})
it('should render as null when filter undefined', function () {
return expect(engine.parseAndRender('{{"foo" | filter1}}', ctx)).to.eventually.equal('foo')
})
it('should throw upon undefined filter when strict_filters set', function () {
return expect(strictEngine.parseAndRender('{{arr | filter1}}', ctx)).to
.be.rejectedWith(/undefined filter: filter1/)
})
})
it('should parse html', function () {
expect(function () {
engine.parse('{{obj}}')
}).to.not.throw()
expect(function () {
engine.parse('<html><head>{{obj}}</head></html>')
}).to.not.throw()
})
it('should render template multiple times', function () {
var template = engine.parse('{{obj}}')
return engine.render(template, ctx)
.then((result) => {
expect(result).to.equal('{"foo":"bar"}')
return engine.render(template, ctx)
})
.then((result) => {
return expect(result).to.equal('{"foo":"bar"}')
})
})
it('should render filters', function () {
var template = engine.parse('<p>{{arr | join: "_"}}</p>')
return expect(engine.render(template, ctx)).to.eventually.equal('<p>-2_a</p>')
})
it('should render accessive filters', function () {
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}'
return expect(engine.parseAndRender(src)).to.eventually.equal('apples')
})
describe('#renderFile()', function () {
it('should render file', function () {
return expect(engine.renderFile('/root/files/foo.html', ctx))
.to.eventually.equal('foo')
})
it('should accept relative path', function () {
return expect(engine.renderFile('files/foo.html'))
.to.eventually.equal('foo')
})
it('should resolve array as root', function () {
engine = Liquid({
root: ['/boo', '/root/'],
extname: '.html'
})
return expect(engine.renderFile('files/foo.html'))
.to.eventually.equal('foo')
})
it('should default root to cwd', function () {
var files = {}
files[process.cwd() + '/foo.html'] = 'FOO'
mock(files)
engine = Liquid({
extname: '.html'
})
return expect(engine.renderFile('foo.html'))
.to.eventually.equal('FOO')
})
it('should render file with context', function () {
return expect(engine.renderFile('/root/files/name.html', ctx)).to.eventually.equal('My name is harttle.')
})
it('should use default extname', function () {
return expect(engine.renderFile('files/name', ctx)).to.eventually.equal('My name is harttle.')
})
it('should throw with lookup list when file not exist', function () {
engine = Liquid({
root: ['/boo', '/root/'],
extname: '.html'
})
return expect(engine.renderFile('/not/exist.html')).to
.be.rejectedWith(/failed to lookup \/not\/exist.html in: \/boo,\/root\//i)
})
it('should throw when file not readable', function () {
return expect(engine.renderFile('/un-readable.html')).to
.be.rejectedWith(/EACCES/)
})
})
describe('strict', function () {
it('should not throw when strict_variables false (default)', function () {
return expect(engine.parseAndRender('before{{notdefined}}after', ctx)).to
.eventually.equal('beforeafter')
})
it('should throw when strict_variables true', function () {
var tpl = engine.parse('before{{notdefined}}after')
var opts = {
strict_variables: true
}
return expect(engine.render(tpl, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/)
})
it('should pass strict_variables to render by parseAndRender', function () {
var html = 'before{{notdefined}}after'
var opts = {
strict_variables: true
}
return expect(engine.parseAndRender(html, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/)
})
})
describe('cache', function () {
it('should be disabled by default', function () {
return engine.renderFile('files/foo')
.then(x => expect(x).to.equal('foo'))
.then(() => mock({
'/root/files/foo.html': 'bar'
}))
.then(() => engine.renderFile('files/foo'))
.then(x => expect(x).to.equal('bar'))
})
it('should respect cache=true option', function () {
engine = Liquid({
root: '/root/',
extname: '.html',
cache: true
})
return engine.renderFile('files/foo')
.then(x => expect(x).to.equal('foo'))
.then(() => mock({
'/root/files/foo.html': 'bar'
}))
.then(() => engine.renderFile('files/foo'))
.then(x => expect(x).to.equal('foo'))
})
})
describe('trim_left, trim_right', function () {
it('should trim_left for tags when trim_left=true', function () {
engine = Liquid({
trim_left: true
})
return expect(engine.parseAndRender(' \n \t{%if true%}foo{%endif%} '))
.to.eventually.equal(' \nfoo ')
})
it('should trim_right for tags when trim_right=true', function () {
engine = Liquid({
trim_right: true
})
return expect(engine.parseAndRender('\t{%if true%}foo{%endif%} \n'))
.to.eventually.equal('\tfoo')
})
it('should trim all blanks before and after when greedy=true', function () {
engine = Liquid({
greedy: true
})
return expect(engine.parseAndRender('\t{%-if true%}foo{%endif-%} \n \n'))
.to.eventually.equal('foo')
})
it('should support trim using markup', function () {
engine = Liquid()
var src = [
'{%- assign username = "John G. Chalmers-Smith" -%}',
'{%- if username and username.length > 10 -%}',
' Wow, {{ username }}, you have a long name!',
'{%- else -%}',
' Hello there!',
'{%- endif -%}\n'
].join('\n')
var dst = ' Wow, John G. Chalmers-Smith, you have a long name!\n'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
})
it('should not trim when not specified', function () {
engine = Liquid()
var src = [
'{% assign username = "John G. Chalmers-Smith" %}',
'{% if username and username.length > 10 %}',
' Wow, {{ username }}, you have a long name!',
'{% else %}',
' Hello there!',
'{% endif %}\n'
].join('\n')
var dst = '\n\n Wow, John G. Chalmers-Smith, you have a long name!\n\n'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
})
})
})
+2
View File
@@ -0,0 +1,2 @@
--require babel-core/register
--recursive
-47
View File
@@ -1,47 +0,0 @@
const chai = require('chai')
const expect = chai.expect
chai.use(require('sinon-chai'))
var filter = require('../src/filter.js')()
var tag = require('../src/tag.js')()
var Template = require('../src/parser.js')
describe('template', function () {
var template
var add = (l, r) => l + r
beforeEach(function () {
filter.clear()
filter.register('add', add)
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 parse output string', function () {
var tpl = template.parseOutput('foo')
expect(tpl.type).to.equal('output')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters).to.deep.equal([])
})
it('should parse output string with a simple filter', function () {
var tpl = template.parseOutput('foo | add: 3, "foo"')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters.length).to.equal(1)
expect(tpl.filters[0].filter).to.equal(add)
})
it('should parse output string with filters', function () {
var tpl = template.parseOutput('foo | add: "|" | add')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters.length).to.equal(2)
})
})
-66
View File
@@ -1,66 +0,0 @@
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)
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
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/)
})
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)
})
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')
})
})
})
-98
View File
@@ -1,98 +0,0 @@
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')
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 register simple tag', function () {
expect(function () {
tag.register('foo', {
render: x => 'bar'
})
}).not.throw()
})
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)
})
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'
}))
})
})
})
-23
View File
@@ -1,23 +0,0 @@
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('')
})
})
-38
View File
@@ -1,38 +0,0 @@
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
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 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 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')
})
})
-103
View File
@@ -1,103 +0,0 @@
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,
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('a')
})
it('should support if 3', function () {
var src = '{% if 2==3 %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should support if 4', function () {
var src = '{% if 1>=2 and one<two %}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('')
})
it('should support if 5', function () {
var src = '{% if one!=two %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('yes')
})
it('should support if 6', function () {
var src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2')
})
it('should support if 7', function () {
var src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('')
})
it('should return true if empty string', function () {
var src = '{%if emptyString%}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a')
})
it('should return else when comparison on null 1', function () {
var src = '{% if null < 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 2', function () {
var src = '{% if null <= 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 3', function () {
var src = '{% if null >= 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 4', function () {
var src = '{% if null > 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 5', function () {
var src = '{% if 10 < null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 6', function () {
var src = '{% if 10 <= null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 7', function () {
var src = '{% if 10 >= null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 8', function () {
var src = '{% if 10 > null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
})
-91
View File
@@ -1,91 +0,0 @@
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')
})
it('should throw when illegal', function () {
mock({
'/illegal.html': '{%include%}'
})
return liquid.renderFile('/illegal.html').catch(function (e) {
expect(e.name).to.equal('ParseError')
expect(e.message).to.match(/illegal token {%include%}/)
})
})
it('should support include with relative path', function () {
mock({
'/bar/foo.html': 'foo',
'/foo/relative.html': 'bar{% include "../bar/foo.html" %}bar'
})
return expect(liquid.renderFile('foo/relative.html')).to
.eventually.equal('barfoobar')
})
it('should support include: hash list', function () {
mock({
'/hash.html': '{% assign name="harttle" %}{% include "user.html", role: "admin", alias: name %}',
'/user.html': '{{name}} : {{role}} : {{alias}}'
})
return expect(liquid.renderFile('hash.html')).to
.eventually.equal('harttle : admin : harttle')
})
it('should support include: parent scope', function () {
mock({
'/scope.html': '{% assign shape="triangle" %}{% assign color="yellow" %}{% include "color.html" %}',
'/color.html': 'color:{{color}}, shape:{{shape}}'
})
return expect(liquid.renderFile('scope.html')).to
.eventually.equal('color:yellow, shape:triangle')
})
it('should support include: 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>')
})
})
-32
View File
@@ -1,32 +0,0 @@
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
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 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')
})
})
-24
View File
@@ -1,24 +0,0 @@
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)
})
})
-76
View File
@@ -1,76 +0,0 @@
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
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 empty tablerow', function () {
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}'
var dst = '<table></table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support empty array', function () {
var src = '{% tablerow i in alpha.z cols:2 %}{{ i }}{% endtablerow %}'
var dst = '<table></table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should throw when tablerow not closed', function () {
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/)
})
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('tablerow should throw on illegal cols 1', function () {
var src = '{% tablerow i in (1..5) cols:0 %}{{ i }}{% endtablerow %}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/illegal cols: 0/)
})
it('tablerow should throw on illegal cols 2', function () {
var src = '{% tablerow i in (1..5) %}{{ i }}{% endtablerow %}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/illegal cols: undefined/)
})
it('should support tablerow with limit', function () {
var src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}'
var dst = '<table>' +
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
'<tr class="row2"><td class="col1">3</td></tr>' +
'</table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support tablerow with offset', function () {
var src = '{% tablerow i in (1..5) cols:2 offset:3 %}{{ i }}{% endtablerow %}'
var dst = '<table>' +
'<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>' +
'</table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
})
-159
View File
@@ -1,159 +0,0 @@
const chai = require('chai')
const parse = require('../src/tokenizer.js').parse
const whiteSpaceCtrl = require('../src/tokenizer.js').whiteSpaceCtrl
const expect = chai.expect
describe('tokenizer', function () {
describe('parse', function () {
it('should handle plain HTML', function () {
var html = '<html><body><p>Lorem Ipsum</p></body></html>'
var tokens = parse(html)
expect(tokens.length).to.equal(1)
expect(tokens[0].value).to.equal(html)
expect(tokens[0].type).to.equal('html')
})
it('should throw when non-string passed in', function () {
expect(function () {
parse({})
}).to.throw('illegal input type')
})
it('should handle tag syntax', function () {
var html = '<p>{% for p in a[1]%}</p>'
var tokens = parse(html)
expect(tokens.length).to.equal(3)
expect(tokens[1].type).to.equal('tag')
expect(tokens[1].value).to.equal('for p in a[1]')
})
it('should handle output syntax', function () {
var html = '<p>{{foo | date: "%Y-%m-%d"}}</p>'
var tokens = parse(html)
expect(tokens.length).to.equal(3)
expect(tokens[1].type).to.equal('output')
expect(tokens[1].value).to.equal('foo | date: "%Y-%m-%d"')
})
it('should handle successive outputs and tags', function () {
var html = '{{foo}}{{bar}}{%foo%}{%bar%}'
var tokens = parse(html)
expect(tokens.length).to.equal(4)
expect(tokens[0].type).to.equal('output')
expect(tokens[3].type).to.equal('tag')
expect(tokens[1].value).to.equal('bar')
expect(tokens[2].value).to.equal('foo')
})
it('should keep white spaces and newlines', function () {
var html = '{%foo%}\n{%bar %} \n {%alice%}'
var tokens = parse(html)
expect(tokens.length).to.equal(5)
expect(tokens[1].type).to.equal('html')
expect(tokens[1].raw).to.equal('\n')
expect(tokens[3].type).to.equal('html')
expect(tokens[3].raw).to.equal(' \n ')
})
it('should handle multiple lines tag', function () {
var html = '{%foo\na:a\nb:1.23\n%}'
var tokens = parse(html)
expect(tokens.length).to.equal(1)
expect(tokens[0].type).to.equal('tag')
expect(tokens[0].args).to.equal('a:a\nb:1.23')
expect(tokens[0].raw).to.equal('{%foo\na:a\nb:1.23\n%}')
})
it('should handle multiple lines output', function () {
var html = '{{foo\n|date:\n"%Y-%m-%d"\n}}'
var tokens = parse(html)
expect(tokens.length).to.equal(1)
expect(tokens[0].type).to.equal('output')
expect(tokens[0].raw).to.equal('{{foo\n|date:\n"%Y-%m-%d"\n}}')
})
})
describe('whitespace control', function () {
it('should not strip by default (tag)', function () {
expect(whiteSpaceCtrl('\n {%foo%} \n')).to.equal('\n {%foo%} \n')
})
it('should strip all blank characters before and after (tag)', function () {
expect(whiteSpaceCtrl(' \t\r{%-foo-%} \t\n')).to.equal('{%-foo-%}')
})
it('should not trim previous/next lines (tag)', function () {
expect(whiteSpaceCtrl(' \t\n {%-foo-%}')).to.equal(' \t\n{%-foo-%}')
expect(whiteSpaceCtrl('{%-foo-%} \n \tfoo')).to.equal('{%-foo-%} \tfoo')
})
it('should trim exactly one trailing CR (tag)', function () {
expect(whiteSpaceCtrl('{%-foo-%} \n\n')).to.equal('{%-foo-%}\n')
})
it('should trim exactly one trailing CR (tag)', function () {
expect(whiteSpaceCtrl('{%-foo-%} \n\n')).to.equal('{%-foo-%}\n')
})
it('should trim all leading/trailing blanks when options.greedy set (tag)', function () {
expect(whiteSpaceCtrl(' \n \n\t\r{%-foo-%}\n \n', {
greedy: true
})).to.equal('{%-foo-%}')
})
it('should strip whitespaces when set trim_left (tag)', function () {
expect(whiteSpaceCtrl('\n {%foo%} \n', {
trim_left: true
})).to.equal('\n{%-foo%} \n')
})
it('should strip whitespaces when set trim_right (tag)', function () {
expect(whiteSpaceCtrl('\n {%foo%} \n', {
trim_right: true
})).to.equal('\n {%foo-%}')
})
it('markup should has priority over options (tag)', function () {
expect(whiteSpaceCtrl('\n {%-foo%} \n', {
trim_left: false
})).to.equal('\n{%-foo%} \n')
})
it('should support a mix of markup and options (tag)', function () {
expect(whiteSpaceCtrl(' {%-foo%} \n', {
trim_left: true,
trim_right: true
})).to.equal('{%-foo-%}')
})
it('should not strip by default (value)', function () {
expect(whiteSpaceCtrl('\n {{foo}} \n')).to.equal('\n {{foo}} \n')
})
it('should strip all blank characters before and after (value)', function () {
expect(whiteSpaceCtrl(' \t\r{{-foo-}} \t\n')).to.equal('{{-foo-}}')
})
it('should not trim previous/next lines (value)', function () {
expect(whiteSpaceCtrl(' \t\n {{-foo-}}')).to.equal(' \t\n{{-foo-}}')
expect(whiteSpaceCtrl('{{-foo-}} \n \tfoo')).to.equal('{{-foo-}} \tfoo')
})
it('should trim exactly one trailing CR (value)', function () {
expect(whiteSpaceCtrl('{{-foo-}} \n\n')).to.equal('{{-foo-}}\n')
})
it('should trim exactly one trailing CR (value)', function () {
expect(whiteSpaceCtrl('{{-foo-}} \n\n')).to.equal('{{-foo-}}\n')
})
it('should trim all leading/trailing blanks when options.greedy set (value)', function () {
expect(whiteSpaceCtrl(' \n \n\t\r{{-foo-}}\n \n', {
greedy: true
})).to.equal('{{-foo-}}')
})
it('should strip whitespaces when set trim_left (value)', function () {
expect(whiteSpaceCtrl('\n {{foo}} \n', {
trim_left: true
})).to.equal('\n{{-foo}} \n')
})
it('should strip whitespaces when set trim_right (value)', function () {
expect(whiteSpaceCtrl('\n {{foo}} \n', {
trim_right: true
})).to.equal('\n {{foo-}}')
})
it('markup should has priority over options (value)', function () {
expect(whiteSpaceCtrl('\n {{-foo}} \n', {
trim_left: false
})).to.equal('\n{{-foo}} \n')
})
it('should support a mix of markup and options (value)', function () {
expect(whiteSpaceCtrl(' {{-foo}} \n', {
trim_left: true,
trim_right: true
})).to.equal('{{-foo-}}')
})
})
})
+96
View File
@@ -0,0 +1,96 @@
import chai from 'chai'
import sinon from 'sinon'
import sinonChai from 'sinon-chai'
import Filter from '../../src/filter.js'
import {factory as scopeFactory} from '../../src/scope.js'
chai.use(sinonChai)
const expect = chai.expect
const filter = Filter()
describe('filter', function () {
let scope
beforeEach(function () {
filter.clear()
scope = scopeFactory()
})
it('should return default filter when not registered', function () {
const 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 parse argument syntax', function () {
filter.register('foo', x => x)
const f = filter.construct('foo: 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 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 call filter with corrct arguments', function () {
const 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)
const 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)
const 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)
const 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)
const 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)
const f = filter.construct('foo: a: "a"')
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal(['\'a\'', '"a"'])
})
it('should not throw undefined filter by default', function () {
expect(filter.construct('undefined').render('foo', scope)).to.equal('foo')
})
})
+93 -36
View File
@@ -1,25 +1,27 @@
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const expect = chai.expect
var liquid = require('..')()
var ctx
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import Liquid from '../../src/index'
chai.use(chaiAsPromised)
const liquid = new Liquid()
const expect = chai.expect
const ctx = {
date: new Date(),
foo: 'bar',
arr: [-2, 'a'],
obj: {
foo: 'bar'
},
func: function () {},
posts: [{
category: 'foo'
}, {
category: 'bar'
}]
}
function test (src, dst) {
ctx = {
date: new Date(),
foo: 'bar',
arr: [-2, 'a'],
obj: {
foo: 'bar'
},
func: function () {},
posts: [{
category: 'foo'
}, {
category: 'bar'
}]
}
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
}
@@ -45,16 +47,58 @@ describe('filters', function () {
it('should return "184" for 183.357', () => test('{{ 183.357 | ceil }}', '184'))
})
describe('concat', function () {
it('should concat arrays', () => test(`
{%- assign fruits = "apples, oranges, peaches" | split: ", " -%}
{%- assign vegetables = "carrots, turnips, potatoes" | split: ", " -%}
{%- assign everything = fruits | concat: vegetables -%}
{%- for item in everything -%}
- {{ item }}
{% endfor -%}`, `- apples
- oranges
- peaches
- carrots
- turnips
- potatoes
`))
it('should support chained concat', () => test(`
{%- assign fruits = "apples, oranges, peaches" | split: ", " -%}
{%- assign vegetables = "carrots, turnips, potatoes" | split: ", " -%}
{%- assign furniture = "chairs, tables, shelves" | split: ", " -%}
{%- assign everything = fruits | concat: vegetables | concat: furniture -%}
{%- for item in everything -%}
- {{ item }}
{% endfor -%}`, `- apples
- oranges
- peaches
- carrots
- turnips
- potatoes
- chairs
- tables
- shelves
`))
})
describe('date', function () {
it('should support date: %a %b %d %Y', function () {
var str = ctx.date.toDateString()
const str = ctx.date.toDateString()
return test('{{ date | date:"%a %b %d %Y"}}', str)
})
it('should create a new Date when given "now"', function () {
return test('{{ "now" | date: "%Y"}}', (new Date()).getFullYear().toString())
})
it('should render as empty string when invalid', function () {
return test('{{ "" | date: "%Y"}}', '')
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"}')
})
})
@@ -66,8 +110,8 @@ describe('filters', function () {
describe('divided_by', function () {
it('should return 2 for 4,2', () => test('{{4 | divided_by: 2}}', '2'))
it('should return 4 for 16,4', () => test('{{16 | divided_by: 4}}', '4'))
it('should return 1 for 5,3', () => test('{{5 | divided_by: 3}}', '1'))
it('should convert string to number', () => test('{{"5" | divided_by: "3"}}', '1'))
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'))
})
describe('downcase', function () {
@@ -86,7 +130,7 @@ describe('filters', function () {
return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara')
})
it('should escape function', function () {
return test('{{ func | escape }}', 'function () {}')
return test('{{ func | escape }}', 'function func() {}')
})
})
@@ -98,8 +142,8 @@ describe('filters', function () {
})
it('should support split/first', function () {
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}'
const src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}'
return test(src, 'apples')
})
@@ -111,19 +155,19 @@ describe('filters', function () {
})
it('should support join', function () {
var src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
'{{ beatles | join: " and " }}'
const src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
'{{ beatles | join: " and " }}'
return test(src, 'John and Paul and George and Ringo')
})
it('should support split/last', function () {
var src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
'{{ my_array|last }}'
const 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 }}'
const src = '{{ " So much room for activities! " | lstrip }}'
return test(src, 'So much room for activities! ')
})
@@ -149,12 +193,12 @@ describe('filters', function () {
})
it('should support string_with_newlines', function () {
var src = '{% capture string_with_newlines %}\n' +
const src = '{% capture string_with_newlines %}\n' +
'Hello\n' +
'there\n' +
'{% endcapture %}' +
'{{ string_with_newlines | newline_to_br }}'
var dst = '<br />' +
const dst = '<br />' +
'Hello<br />' +
'there<br />'
return test(src, dst)
@@ -257,9 +301,21 @@ describe('filters', function () {
describe('strip_html', function () {
it('should strip all tags', function () {
return test('{{ "Have <em>you</em> read <strong>Ulysses</strong>?" | strip_html }}',
return test('{{ "Have <em>you</em> read <cite><a href=&quot;https://en.wikipedia.org/wiki/Ulysses_(novel)&quot;>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 }}', '')
})
@@ -350,6 +406,7 @@ describe('filters', function () {
liquid.registerFilter('obj_test', function () {
return Array.prototype.slice.call(arguments).join(',')
})
it('should support object', () => test('{{ "a" | obj_test: k1: "v1", k2: "v2" }}', 'a,k1,v1,k2,v2'))
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'))
})
})
+41
View File
@@ -0,0 +1,41 @@
import Liquid from '../../src/index.js'
import mock from 'mock-fs'
import chai from 'chai'
const expect = chai.expect
describe('Liquid', function () {
describe('#constructor()', function () {
it('should throw on illegal root', function () {
expect(() => {
new Liquid({root: {}}) // eslint-disable-line
}).to.throw(/illegal root/)
})
})
describe('#express()', function () {
const liquid = new Liquid({root: '/root'})
const render = liquid.express()
before(function () {
mock({
'/root/foo': 'foo'
})
})
after(function () {
mock.restore()
})
it('should render single template', function (done) {
render.call({root: '.'}, 'foo', null, (err, result) => {
if (err) return done(err)
expect(result).to.equal('foo')
done()
})
})
it('should render single template with Array-typed root', function (done) {
render.call({root: ['.']}, 'foo', null, (err, result) => {
if (err) return done(err)
expect(result).to.equal('foo')
done()
})
})
})
})
+6 -6
View File
@@ -1,7 +1,7 @@
const chai = require('chai')
const expect = chai.expect
var lexical = require('../src/lexical.js')
const lexical = require('../../src/lexical.js')
describe('lexical', function () {
it('should test filter syntax', function () {
@@ -105,26 +105,26 @@ describe('lexical', function () {
})
it('should throw if non-literal', function () {
var fn = () => lexical.parseLiteral('a')
const 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')
const 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')
const 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')
const 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')
const match = lexical.matchValue('var-1')
expect(match && match[0]).to.equal('var-1')
})
})
+44
View File
@@ -0,0 +1,44 @@
import chai from 'chai'
import mock from 'mock-fs'
import Liquid from '../../../src'
import chaiAsPromised from 'chai-as-promised'
const expect = chai.expect
chai.use(chaiAsPromised)
describe('cache options', function () {
let 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'))
})
})
+36
View File
@@ -0,0 +1,36 @@
import Liquid from '../../../src'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('strict options', function () {
let engine
const 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 () {
const tpl = engine.parse('before{{notdefined}}after')
const 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 () {
const html = 'before{{notdefined}}after'
const opts = {
strict_variables: true
}
return expect(engine.parseAndRender(html, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/)
})
})

Some files were not shown because too many files have changed in this diff Show More