mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-16 12:50:38 -07:00
refactor: import rollup
This commit is contained in:
@@ -1,3 +1,11 @@
|
||||
{
|
||||
"presets": ["es2015"]
|
||||
"presets": ["es2015"],
|
||||
"plugins": [
|
||||
["transform-runtime", {
|
||||
"helpers": false,
|
||||
"polyfill": false,
|
||||
"regenerator": true,
|
||||
"moduleName": "babel-runtime"
|
||||
}]
|
||||
]
|
||||
}
|
||||
|
||||
+2
-1
@@ -10,6 +10,7 @@
|
||||
"promise"
|
||||
],
|
||||
"rules": {
|
||||
"no-var": 2
|
||||
"no-var": 2,
|
||||
"prefer-const": 2
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/coverage
|
||||
/src
|
||||
/test
|
||||
.*
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
<!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>
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
const Liquid = require('../..')
|
||||
// const Liquid = require('../..')
|
||||
const Liquid = require('../../dist/liquid.common.js')
|
||||
|
||||
let engine = new Liquid({
|
||||
const engine = new Liquid({
|
||||
root: __dirname,
|
||||
extname: '.liquid'
|
||||
})
|
||||
let ctx = {
|
||||
const ctx = {
|
||||
todos: ['fork and clone', 'make it better', 'make a pull request'],
|
||||
title: 'Welcome to liquidjs!'
|
||||
}
|
||||
|
||||
Vendored
+3738
File diff suppressed because it is too large
Load Diff
Vendored
+1
File diff suppressed because one or more lines are too long
Vendored
+3552
-2578
File diff suppressed because it is too large
Load Diff
Vendored
+1
File diff suppressed because one or more lines are too long
Vendored
+2
-1
File diff suppressed because one or more lines are too long
Vendored
+1
File diff suppressed because one or more lines are too long
+14
-18
@@ -2,16 +2,14 @@
|
||||
"name": "liquidjs",
|
||||
"version": "5.3.0-0",
|
||||
"description": "Liquid template engine by pure JavaScript: compatible to shopify, easy to extend.",
|
||||
"main": "build/index.js",
|
||||
"main": "dist/liquid.common.js",
|
||||
"module": "src/index.js",
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"lint": "eslint src/ test/",
|
||||
"test": "mocha --require babel-core/register --recursive",
|
||||
"coverage": "nyc report --require babel-core/register mocha test/ --recursive ",
|
||||
"coveralls": "nyc report --reporter=text-lcov --require babel-core/register mocha test/ --recursive | coveralls",
|
||||
"dist": "npm run babelify && npm run browserify && npm run uglify",
|
||||
"babelify": "babel src -d build",
|
||||
"browserify": "browserify src/index.js -s Liquid --ignore path -t [ babelify --presets [ es2015 ] ] > dist/liquid.js",
|
||||
"uglify": "uglifyjs dist/liquid.js --compress warnings=false --mangle toplevel --output dist/liquid.min.js",
|
||||
"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",
|
||||
@@ -39,21 +37,15 @@
|
||||
"url": "https://github.com/harttle/liquidjs/issues"
|
||||
},
|
||||
"homepage": "https://github.com/harttle/liquidjs#readme",
|
||||
"dependencies": {
|
||||
"resolve-url": "^0.2.1"
|
||||
},
|
||||
"browser": {
|
||||
"fs": false
|
||||
},
|
||||
"devDependencies": {
|
||||
"babel-core": "^6.26.3",
|
||||
"babel-plugin-external-helpers": "^6.22.0",
|
||||
"babel-plugin-transform-runtime": "^6.23.0",
|
||||
"babel-preset-env": "^1.7.0",
|
||||
"babel-preset-es2015": "^6.24.1",
|
||||
"babelify": "^8.0.0",
|
||||
"browserify": "^16.2.2",
|
||||
"chai": "^4.1.2",
|
||||
"chai-as-promised": "^7.1.1",
|
||||
"coveralls": "^3.0.0",
|
||||
"cross-env": "^5.1.3",
|
||||
"eslint": "^5.2.0",
|
||||
"eslint-config-standard": "^11.0.0",
|
||||
"eslint-plugin-import": "^2.7.0",
|
||||
@@ -63,14 +55,18 @@
|
||||
"eslint-plugin-standard": "^3.0.1",
|
||||
"express": "^4.16.1",
|
||||
"http-server": "^0.11.1",
|
||||
"istanbul": "^0.4.5",
|
||||
"jsdom": "^11.5.1",
|
||||
"mocha": "^5.2.0",
|
||||
"mock-fs": "^4.4.1",
|
||||
"nyc": "^12.0.2",
|
||||
"regenerator-runtime": "^0.12.1",
|
||||
"rollup": "^0.64.1",
|
||||
"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",
|
||||
"uglify-js": "^3.4.5"
|
||||
"supertest": "^3.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import shim from 'rollup-plugin-shim'
|
||||
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),
|
||||
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
|
||||
}]
|
||||
+18
-18
@@ -1,17 +1,17 @@
|
||||
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} from './util/underscore.js'
|
||||
|
||||
let valueRE = new RegExp(`${lexical.value.source}`, 'g')
|
||||
const valueRE = new RegExp(`${lexical.value.source}`, 'g')
|
||||
|
||||
module.exports = function (options) {
|
||||
options = _.assign({}, options)
|
||||
export default function (options) {
|
||||
options = assign({}, options)
|
||||
let filters = {}
|
||||
|
||||
let _filterInstance = {
|
||||
const _filterInstance = {
|
||||
render: function (output, scope) {
|
||||
let 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)
|
||||
},
|
||||
@@ -19,9 +19,9 @@ module.exports = function (options) {
|
||||
let match = lexical.filterLine.exec(str)
|
||||
assert(match, 'illegal filter: ' + str)
|
||||
|
||||
let name = match[1]
|
||||
let argList = match[2] || ''
|
||||
let 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,12 +32,12 @@ module.exports = function (options) {
|
||||
return this
|
||||
}
|
||||
|
||||
let args = []
|
||||
const args = []
|
||||
while ((match = valueRE.exec(argList.trim()))) {
|
||||
let v = match[0]
|
||||
let re = new RegExp(`${v}\\s*:`, 'g')
|
||||
let keyMatch = re.exec(match.input)
|
||||
let currentMatchIsKey = keyMatch && keyMatch.index === match.index
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ module.exports = function (options) {
|
||||
}
|
||||
|
||||
function construct (str) {
|
||||
let instance = Object.create(_filterInstance)
|
||||
const instance = Object.create(_filterInstance)
|
||||
return instance.parse(str)
|
||||
}
|
||||
|
||||
|
||||
+15
-17
@@ -1,16 +1,15 @@
|
||||
'use strict'
|
||||
const strftime = require('./util/strftime.js')
|
||||
const _ = require('./util/underscore.js')
|
||||
const isTruthy = require('./syntax.js').isTruthy
|
||||
import strftime from './util/strftime.js'
|
||||
import * as _ from './util/underscore.js'
|
||||
import {isTruthy} from './syntax.js'
|
||||
|
||||
let escapeMap = {
|
||||
const escapeMap = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": '''
|
||||
}
|
||||
let unescapeMap = {
|
||||
const unescapeMap = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
@@ -18,7 +17,7 @@ let unescapeMap = {
|
||||
''': "'"
|
||||
}
|
||||
|
||||
let filters = {
|
||||
const filters = {
|
||||
'abs': v => Math.abs(v),
|
||||
'append': (v, arg) => v + arg,
|
||||
'capitalize': str => stringify(str).charAt(0).toUpperCase() + str.slice(1),
|
||||
@@ -57,7 +56,7 @@ let filters = {
|
||||
'replace_first': (v, arg1, arg2) => stringify(v).replace(arg1, arg2),
|
||||
'reverse': v => v.reverse(),
|
||||
'round': (v, arg) => {
|
||||
let 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+$/, ''),
|
||||
@@ -79,13 +78,13 @@ let filters = {
|
||||
},
|
||||
'truncatewords': (v, l, o) => {
|
||||
if (o === undefined) o = '...'
|
||||
let arr = v.split(' ')
|
||||
const arr = v.split(' ')
|
||||
let ret = arr.slice(0, l).join(' ')
|
||||
if (arr.length > l) ret += o
|
||||
return ret
|
||||
},
|
||||
'uniq': function (arr) {
|
||||
let u = {}
|
||||
const u = {}
|
||||
return (arr || []).filter(val => {
|
||||
if (u.hasOwnProperty(val)) {
|
||||
return false
|
||||
@@ -107,7 +106,7 @@ function unescape (str) {
|
||||
}
|
||||
|
||||
function getFixed (v) {
|
||||
let p = (v + '').split('.')
|
||||
const p = (v + '').split('.')
|
||||
return (p.length > 1) ? p[1].length : 0
|
||||
}
|
||||
|
||||
@@ -121,18 +120,17 @@ function stringify (obj) {
|
||||
|
||||
function bindFixed (cb) {
|
||||
return (l, r) => {
|
||||
let f = getMaxFixed(l, r)
|
||||
const f = getMaxFixed(l, r)
|
||||
return cb(l, r).toFixed(f)
|
||||
}
|
||||
}
|
||||
|
||||
function registerAll (liquid) {
|
||||
return _.forOwn(filters, (func, name) => liquid.registerFilter(name, func))
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
+73
-90
@@ -1,22 +1,24 @@
|
||||
import Scope from './scope'
|
||||
import _ from './util/underscore.js'
|
||||
import 'regenerator-runtime/runtime'
|
||||
import * as Scope from './scope'
|
||||
import {get as httpGet} from './util/http.js'
|
||||
import * as _ from './util/underscore.js'
|
||||
import assert from './util/assert.js'
|
||||
import tokenizer from './tokenizer.js'
|
||||
import * as tokenizer from './tokenizer.js'
|
||||
import {statFileAsync, readFileAsync} from './util/fs.js'
|
||||
import path from 'path'
|
||||
import {valid as isValidUrl, extname, resolve} from './util/url.js'
|
||||
import lexical from './lexical.js'
|
||||
import * as lexical from './lexical.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 tags from './tags'
|
||||
import filters from './filters'
|
||||
import {anySeries} from './util/promise.js'
|
||||
import {ParseError, TokenizationEroor, RenderBreakError, AssertionError} from './util/error.js'
|
||||
import {ParseError, TokenizationError, RenderBreakError, AssertionError} from './util/error.js'
|
||||
import tags from './tags/index.js'
|
||||
import filters from './filters.js'
|
||||
|
||||
let _engine = {
|
||||
const _engine = {
|
||||
init: function (tag, filter, options) {
|
||||
if (options.cache) {
|
||||
this.cache = {}
|
||||
@@ -27,32 +29,31 @@ let _engine = {
|
||||
this.parser = Parser(tag, filter)
|
||||
this.renderer = Render()
|
||||
|
||||
tags(this)
|
||||
filters(this)
|
||||
tags(this, Liquid)
|
||||
filters(this, Liquid)
|
||||
|
||||
return this
|
||||
},
|
||||
parse: function (html, filepath) {
|
||||
let tokens = tokenizer.parse(html, filepath, this.options)
|
||||
const tokens = tokenizer.parse(html, filepath, this.options)
|
||||
return this.parser.parse(tokens)
|
||||
},
|
||||
render: function (tpl, ctx, opts) {
|
||||
opts = _.assign({}, this.options, opts)
|
||||
let scope = Scope.factory(ctx, opts)
|
||||
const 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))
|
||||
parseAndRender: async function (html, ctx, opts) {
|
||||
const tpl = await this.parse(html)
|
||||
return this.render(tpl, ctx, opts)
|
||||
},
|
||||
renderFile: function (filepath, ctx, opts) {
|
||||
renderFile: async function (filepath, ctx, opts) {
|
||||
opts = _.assign({}, opts)
|
||||
return this.getTemplate(filepath, opts.root)
|
||||
.then(templates => this.render(templates, ctx, opts))
|
||||
const templates = await this.getTemplate(filepath, opts.root)
|
||||
return this.render(templates, ctx, opts)
|
||||
},
|
||||
evalValue: function (str, scope) {
|
||||
let tpl = this.parser.parseValue(str.trim())
|
||||
const tpl = this.parser.parseValue(str.trim())
|
||||
return this.renderer.evalValue(tpl, scope)
|
||||
},
|
||||
registerFilter: function (name, filter) {
|
||||
@@ -64,39 +65,33 @@ let _engine = {
|
||||
lookup: function (filepath, root) {
|
||||
root = this.options.root.concat(root || [])
|
||||
root = _.uniq(root)
|
||||
let paths = root.map(root => path.resolve(root, filepath))
|
||||
return anySeries(paths, path => statFileAsync(path).then(() => path))
|
||||
.catch((e) => {
|
||||
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
|
||||
})
|
||||
}
|
||||
})
|
||||
},
|
||||
getTemplate: function (filepath, root) {
|
||||
return typeof XMLHttpRequest === 'undefined'
|
||||
? this.getTemplateFromFile(filepath, root)
|
||||
: this.getTemplateFromUrl(filepath, root)
|
||||
},
|
||||
getTemplateFromFile: function (filepath, root) {
|
||||
getTemplateFromFile: async function (filepath, root) {
|
||||
if (!path.extname(filepath)) {
|
||||
filepath += this.options.extname
|
||||
}
|
||||
return this
|
||||
.lookup(filepath, root)
|
||||
.then(filepath => {
|
||||
if (this.options.cache) {
|
||||
let 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))
|
||||
}
|
||||
})
|
||||
filepath = await this.lookup(filepath, root)
|
||||
return this.respectCache(filepath, async () => {
|
||||
const str = await readFileAsync(filepath)
|
||||
return this.parse(str, filepath)
|
||||
})
|
||||
},
|
||||
getTemplateFromUrl: function (filepath, root) {
|
||||
getTemplateFromUrl: async function (filepath, root) {
|
||||
let fullUrl
|
||||
if (isValidUrl(filepath)) {
|
||||
fullUrl = filepath
|
||||
@@ -106,47 +101,41 @@ let _engine = {
|
||||
}
|
||||
fullUrl = resolve(root || this.options.root, filepath)
|
||||
}
|
||||
if (this.options.cache) {
|
||||
let tpl = this.cache[filepath]
|
||||
if (tpl) {
|
||||
return Promise.resolve(tpl)
|
||||
}
|
||||
return this.respectCache(
|
||||
filepath,
|
||||
async () => this.parse(await httpGet(fullUrl))
|
||||
)
|
||||
},
|
||||
respectCache: async function (key, getter) {
|
||||
const cacheEnabled = this.options.cache
|
||||
if (cacheEnabled && this.cache[key]) {
|
||||
return this.cache[key]
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
let xhr = new XMLHttpRequest()
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
let tpl = this.parse(xhr.responseText)
|
||||
if (this.options.cache) {
|
||||
this.cache[filepath] = tpl
|
||||
}
|
||||
resolve(tpl)
|
||||
} else {
|
||||
reject(new Error(xhr.statusText))
|
||||
}
|
||||
}
|
||||
xhr.onerror = () => {
|
||||
reject(new Error('An error occurred whilst sending the response.'))
|
||||
}
|
||||
xhr.open('GET', fullUrl)
|
||||
xhr.send()
|
||||
})
|
||||
const value = await getter()
|
||||
if (cacheEnabled) {
|
||||
this.cache[key] = value
|
||||
}
|
||||
return value
|
||||
},
|
||||
express: function (opts) {
|
||||
opts = opts || {}
|
||||
let self = this
|
||||
return function (filePath, ctx, callback) {
|
||||
const self = this
|
||||
return function (filePath, ctx, cb) {
|
||||
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))
|
||||
self.renderFile(filePath, ctx, opts).then(html => cb(null, html), cb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function factory (options) {
|
||||
function normalizeStringArray (value) {
|
||||
if (Array.isArray(value)) return value
|
||||
if (_.isString(value)) return [value]
|
||||
return []
|
||||
}
|
||||
|
||||
export default function Liquid (options) {
|
||||
options = _.assign({
|
||||
root: ['.'],
|
||||
cache: false,
|
||||
@@ -162,29 +151,23 @@ function factory (options) {
|
||||
}, options)
|
||||
options.root = normalizeStringArray(options.root)
|
||||
|
||||
let engine = Object.create(_engine)
|
||||
const 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 []
|
||||
}
|
||||
|
||||
const Types = {
|
||||
Liquid.isTruthy = isTruthy
|
||||
Liquid.isFalsy = isFalsy
|
||||
Liquid.evalExp = evalExp
|
||||
Liquid.evalValue = evalValue
|
||||
Liquid.Types = {
|
||||
ParseError,
|
||||
TokenizationEroor,
|
||||
TokenizationError,
|
||||
RenderBreakError,
|
||||
AssertionError
|
||||
AssertionError,
|
||||
AssignScope: Object.create(null),
|
||||
CaptureScope: Object.create(null),
|
||||
IncrementScope: Object.create(null),
|
||||
DecrementScope: Object.create(null)
|
||||
}
|
||||
|
||||
factory.isTruthy = isTruthy
|
||||
factory.isFalsy = isFalsy
|
||||
factory.evalExp = evalExp
|
||||
factory.evalValue = evalValue
|
||||
factory.Types = Types
|
||||
factory.lexical = lexical
|
||||
|
||||
module.exports = factory
|
||||
Liquid.lexical = lexical
|
||||
|
||||
+37
-67
@@ -1,75 +1,75 @@
|
||||
// quote related
|
||||
let singleQuoted = /'[^']*'/
|
||||
let doubleQuoted = /"[^"]*"/
|
||||
let quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
|
||||
let 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
|
||||
let integer = /-?\d+/
|
||||
let number = /-?\d+\.?\d*|\.?\d+/
|
||||
let bool = /true|false/
|
||||
export const integer = /-?\d+/
|
||||
export const number = /-?\d+\.?\d*|\.?\d+/
|
||||
export const bool = /true|false/
|
||||
|
||||
// peoperty access
|
||||
let identifier = /[\w-]+[?]?/
|
||||
let subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`)
|
||||
let literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`)
|
||||
let variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`)
|
||||
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
|
||||
let rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`)
|
||||
let range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`)
|
||||
let 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})\\)`)
|
||||
|
||||
let value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
|
||||
export const value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
|
||||
|
||||
// hash related
|
||||
let hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`)
|
||||
let 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
|
||||
let tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`)
|
||||
let literalLine = new RegExp(`^${literal.source}$`, 'i')
|
||||
let variableLine = new RegExp(`^${variable.source}$`)
|
||||
let numberLine = new RegExp(`^${number.source}$`)
|
||||
let boolLine = new RegExp(`^${bool.source}$`, 'i')
|
||||
let quotedLine = new RegExp(`^${quoted.source}$`)
|
||||
let rangeLine = new RegExp(`^${rangeCapture.source}$`)
|
||||
let 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
|
||||
let valueDeclaration = new RegExp(`(?:${identifier.source}\\s*:\\s*)?${value.source}`)
|
||||
let valueList = new RegExp(`${valueDeclaration.source}(\\s*,\\s*${valueDeclaration.source})*`)
|
||||
let filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g')
|
||||
let filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`)
|
||||
let 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}$`)
|
||||
|
||||
let 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) {
|
||||
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
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
module.exports = function (isTruthy) {
|
||||
export default function (isTruthy) {
|
||||
return {
|
||||
'==': (l, r) => l === r,
|
||||
'!=': (l, r) => l !== r,
|
||||
|
||||
+11
-11
@@ -1,9 +1,9 @@
|
||||
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 {ParseError} from './util/error.js'
|
||||
import assert from './util/assert.js'
|
||||
|
||||
module.exports = function (Tag, Filter) {
|
||||
let stream = {
|
||||
export default function (Tag, Filter) {
|
||||
const stream = {
|
||||
init: function (tokens) {
|
||||
this.tokens = tokens
|
||||
this.handlers = {}
|
||||
@@ -14,7 +14,7 @@ module.exports = function (Tag, Filter) {
|
||||
return this
|
||||
},
|
||||
trigger: function (event, arg) {
|
||||
let h = this.handlers[event]
|
||||
const h = this.handlers[event]
|
||||
if (typeof h === 'function') {
|
||||
h(arg)
|
||||
return true
|
||||
@@ -29,7 +29,7 @@ module.exports = function (Tag, Filter) {
|
||||
this.trigger(`tag:${token.name}`, token)) {
|
||||
continue
|
||||
}
|
||||
let template = parseToken(token, this.tokens)
|
||||
const template = parseToken(token, this.tokens)
|
||||
this.trigger('template', template)
|
||||
}
|
||||
if (!this.stopRequested) this.trigger('end')
|
||||
@@ -43,7 +43,7 @@ module.exports = function (Tag, Filter) {
|
||||
|
||||
function parse (tokens) {
|
||||
let token
|
||||
let templates = []
|
||||
const templates = []
|
||||
while ((token = tokens.shift())) {
|
||||
templates.push(parseToken(token, tokens))
|
||||
}
|
||||
@@ -76,10 +76,10 @@ module.exports = function (Tag, Filter) {
|
||||
let match = lexical.matchValue(str)
|
||||
assert(match, `illegal value string: ${str}`)
|
||||
|
||||
let initial = match[0]
|
||||
const initial = match[0]
|
||||
str = str.substr(match.index + match[0].length)
|
||||
|
||||
let filters = []
|
||||
const filters = []
|
||||
while ((match = lexical.filter.exec(str))) {
|
||||
filters.push([match[0].trim()])
|
||||
}
|
||||
@@ -92,7 +92,7 @@ module.exports = function (Tag, Filter) {
|
||||
}
|
||||
|
||||
function parseStream (tokens) {
|
||||
let s = Object.create(stream)
|
||||
const s = Object.create(stream)
|
||||
return s.init(tokens)
|
||||
}
|
||||
|
||||
|
||||
+36
-41
@@ -1,67 +1,62 @@
|
||||
const Syntax = require('./syntax.js')
|
||||
const mapSeries = require('./util/promise.js').mapSeries
|
||||
const RenderBreakError = require('./util/error.js').RenderBreakError
|
||||
const _ = require('./util/underscore.js')
|
||||
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} from './util/underscore.js'
|
||||
import assert from './util/assert.js'
|
||||
|
||||
let render = {
|
||||
|
||||
renderTemplates: function (templates, scope) {
|
||||
const render = {
|
||||
renderTemplates: async function (templates, scope) {
|
||||
assert(scope, 'unable to evalTemplates: scope undefined')
|
||||
|
||||
let 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 === 'value') {
|
||||
return this.renderValue(template, scope)
|
||||
} else { // template.type === 'html'
|
||||
return Promise.resolve(template.value)
|
||||
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)
|
||||
},
|
||||
|
||||
renderValue: function (template, scope) {
|
||||
return Promise.resolve()
|
||||
.then(() => this.evalValue(template, scope))
|
||||
.then(partial => partial === undefined ? '' : _.stringify(partial))
|
||||
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 () {
|
||||
let instance = Object.create(render)
|
||||
export default function () {
|
||||
const instance = Object.create(render)
|
||||
return instance
|
||||
}
|
||||
|
||||
module.exports = factory
|
||||
|
||||
+14
-22
@@ -1,19 +1,18 @@
|
||||
'use strict'
|
||||
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'
|
||||
|
||||
let Scope = {
|
||||
const Scope = {
|
||||
getAll: function () {
|
||||
return this.contexts.reduce((ctx, val) => Object.assign(ctx, val), Object.create(null))
|
||||
},
|
||||
get: function (path) {
|
||||
let paths = this.propertyAccessSeq(path)
|
||||
let scope = this.findContextFor(paths[0]) || _.last(this.contexts)
|
||||
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) {
|
||||
let paths = this.propertyAccessSeq(path)
|
||||
const paths = this.propertyAccessSeq(path)
|
||||
let scope = this.findContextFor(paths[0]) || _.last(this.contexts)
|
||||
paths.some((key, i) => {
|
||||
if (!_.isObject(scope)) {
|
||||
@@ -39,7 +38,7 @@ let Scope = {
|
||||
if (!arguments.length) {
|
||||
return this.contexts.pop()
|
||||
}
|
||||
let i = this.contexts.findIndex(scope => scope === ctx)
|
||||
const i = this.contexts.findIndex(scope => scope === ctx)
|
||||
if (i === -1) {
|
||||
throw new TypeError('scope not found, cannot pop')
|
||||
}
|
||||
@@ -48,7 +47,7 @@ let Scope = {
|
||||
findContextFor: function (key, filter) {
|
||||
filter = filter || (() => true)
|
||||
for (let i = this.contexts.length - 1; i >= 0; i--) {
|
||||
let candidate = this.contexts[i]
|
||||
const candidate = this.contexts[i]
|
||||
if (!filter(candidate)) continue
|
||||
if (key in candidate) {
|
||||
return candidate
|
||||
@@ -89,7 +88,7 @@ let Scope = {
|
||||
*/
|
||||
propertyAccessSeq: function (str) {
|
||||
str = String(str)
|
||||
let seq = []
|
||||
const seq = []
|
||||
let name = ''
|
||||
let j
|
||||
let i = 0
|
||||
@@ -98,7 +97,7 @@ let Scope = {
|
||||
case '[':
|
||||
push()
|
||||
|
||||
let 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}`)
|
||||
@@ -155,23 +154,16 @@ function matchRightBracket (str, begin) {
|
||||
return -1
|
||||
}
|
||||
|
||||
exports.factory = function (ctx, opts) {
|
||||
let defaultOptions = {
|
||||
export function factory (ctx, opts) {
|
||||
const defaultOptions = {
|
||||
dynamicPartials: true,
|
||||
strict_variables: false,
|
||||
strict_filters: false,
|
||||
blocks: {},
|
||||
root: []
|
||||
}
|
||||
let scope = Object.create(Scope)
|
||||
const scope = Object.create(Scope)
|
||||
scope.opts = _.assign(defaultOptions, opts)
|
||||
scope.contexts = [ctx || {}]
|
||||
return scope
|
||||
}
|
||||
|
||||
exports.types = {
|
||||
AssignScope: Object.create(null),
|
||||
CaptureScope: Object.create(null),
|
||||
IncrementScope: Object.create(null),
|
||||
DecrementScope: Object.create(null)
|
||||
}
|
||||
|
||||
+18
-20
@@ -1,26 +1,28 @@
|
||||
const operators = require('./operators.js')(isTruthy)
|
||||
const lexical = require('./lexical.js')
|
||||
const assert = require('./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')
|
||||
let operatorREs = lexical.operators
|
||||
const operatorREs = lexical.operators
|
||||
let match
|
||||
for (let i = 0; i < operatorREs.length; i++) {
|
||||
let operatorRE = operatorREs[i]
|
||||
let expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`)
|
||||
const operatorRE = operatorREs[i]
|
||||
const expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`)
|
||||
if ((match = exp.match(expRE))) {
|
||||
let l = evalExp(match[1], scope)
|
||||
let op = operators[match[2].trim()]
|
||||
let 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))) {
|
||||
let low = evalValue(match[1], scope)
|
||||
let high = evalValue(match[2], scope)
|
||||
let range = []
|
||||
const low = evalValue(match[1], scope)
|
||||
const high = evalValue(match[2], scope)
|
||||
const range = []
|
||||
for (let j = low; j <= high; j++) {
|
||||
range.push(j)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
+18
-19
@@ -1,38 +1,37 @@
|
||||
'use strict'
|
||||
const lexical = require('./lexical.js')
|
||||
const Syntax = require('./syntax.js')
|
||||
const assert = require('./util/assert.js')
|
||||
import {hashCapture} from './lexical.js'
|
||||
import {evalValue} from './syntax.js'
|
||||
import assert from './util/assert.js'
|
||||
|
||||
function hash (markup, scope) {
|
||||
let obj = {}
|
||||
const obj = {}
|
||||
let match
|
||||
lexical.hashCapture.lastIndex = 0
|
||||
while ((match = lexical.hashCapture.exec(markup))) {
|
||||
let k = match[1]
|
||||
let v = match[2]
|
||||
obj[k] = Syntax.evalValue(v, scope)
|
||||
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 () {
|
||||
export default function () {
|
||||
let tagImpls = {}
|
||||
|
||||
let _tagInstance = {
|
||||
render: function (scope) {
|
||||
let obj = hash(this.token.args, scope)
|
||||
let 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
|
||||
|
||||
let tagImpl = tagImpls[this.name]
|
||||
const tagImpl = tagImpls[this.name]
|
||||
assert(tagImpl, `tag ${this.name} not found`)
|
||||
this.tagImpl = Object.create(tagImpl)
|
||||
if (this.tagImpl.parse) {
|
||||
@@ -46,7 +45,7 @@ module.exports = function () {
|
||||
}
|
||||
|
||||
function construct (token, tokens) {
|
||||
let instance = Object.create(_tagInstance)
|
||||
const instance = Object.create(_tagInstance)
|
||||
instance.parse(token, tokens)
|
||||
return instance
|
||||
}
|
||||
|
||||
+6
-6
@@ -1,19 +1,19 @@
|
||||
import {lexical} from '../index'
|
||||
import assert from '../util/assert.js'
|
||||
import {types} from '../scope'
|
||||
|
||||
const re = new RegExp(`(${lexical.identifier.source})\\s*=(.*)`)
|
||||
export default function (liquid, Liquid) {
|
||||
const rIdentifier = Liquid.lexical.identifier
|
||||
const re = new RegExp(`(${rIdentifier.source})\\s*=(.*)`)
|
||||
const {AssignScope} = Liquid.Types
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('assign', {
|
||||
parse: function (token) {
|
||||
let match = token.args.match(re)
|
||||
const match = token.args.match(re)
|
||||
assert(match, `illegal token ${token.raw}`)
|
||||
this.key = match[1]
|
||||
this.value = match[2]
|
||||
},
|
||||
render: function (scope) {
|
||||
let ctx = Object.create(types.AssignScope)
|
||||
const ctx = Object.create(AssignScope)
|
||||
ctx[this.key] = liquid.evalValue(this.value, scope)
|
||||
scope.push(ctx)
|
||||
return Promise.resolve('')
|
||||
|
||||
+13
-16
@@ -1,20 +1,19 @@
|
||||
'use strict'
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const re = new RegExp(`(${lexical.identifier.source})`)
|
||||
const assert = require('../util/assert.js')
|
||||
const types = require('../scope.js').types
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
export default function (liquid, Liquid) {
|
||||
const rIdentifier = Liquid.lexical.identifier
|
||||
const re = new RegExp(`(${rIdentifier.source})`)
|
||||
const {CaptureScope} = Liquid.Types
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('capture', {
|
||||
parse: function (tagToken, remainTokens) {
|
||||
let match = tagToken.args.match(re)
|
||||
const match = tagToken.args.match(re)
|
||||
assert(match, `${tagToken.args} not valid identifier`)
|
||||
|
||||
this.variable = match[1]
|
||||
this.templates = []
|
||||
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
stream.on('tag:endcapture', token => stream.stop())
|
||||
.on('template', tpl => this.templates.push(tpl))
|
||||
.on('end', x => {
|
||||
@@ -22,13 +21,11 @@ module.exports = function (liquid) {
|
||||
})
|
||||
stream.start()
|
||||
},
|
||||
render: function (scope, hash) {
|
||||
return liquid.renderer.renderTemplates(this.templates, scope)
|
||||
.then((html) => {
|
||||
let ctx = Object.create(types.CaptureScope)
|
||||
ctx[this.variable] = html
|
||||
scope.push(ctx)
|
||||
})
|
||||
render: async function (scope, hash) {
|
||||
const html = await liquid.renderer.renderTemplates(this.templates, scope)
|
||||
const ctx = Object.create(CaptureScope)
|
||||
ctx[this.variable] = html
|
||||
scope.push(ctx)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+5
-7
@@ -1,6 +1,4 @@
|
||||
import Liquid from '..'
|
||||
|
||||
module.exports = function (liquid) {
|
||||
export default function (liquid, Liquid) {
|
||||
liquid.registerTag('case', {
|
||||
|
||||
parse: function (tagToken, remainTokens) {
|
||||
@@ -9,7 +7,7 @@ module.exports = function (liquid) {
|
||||
this.elseTemplates = []
|
||||
|
||||
let p = []
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('tag:when', token => {
|
||||
this.cases.push({
|
||||
val: token.args,
|
||||
@@ -28,9 +26,9 @@ module.exports = function (liquid) {
|
||||
|
||||
render: function (scope, hash) {
|
||||
for (let i = 0; i < this.cases.length; i++) {
|
||||
let branch = this.cases[i]
|
||||
let val = Liquid.evalExp(branch.val, scope)
|
||||
let cond = Liquid.evalExp(this.cond, scope)
|
||||
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)
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
module.exports = function (liquid) {
|
||||
export default function (liquid) {
|
||||
liquid.registerTag('comment', {
|
||||
parse: function (tagToken, remainTokens) {
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
stream
|
||||
.on('token', token => {
|
||||
if (token.name === 'endcomment') stream.stop()
|
||||
|
||||
+12
-12
@@ -1,10 +1,10 @@
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const groupRE = new RegExp(`^(?:(${lexical.value.source})\\s*:\\s*)?(.*)$`)
|
||||
const candidatesRE = new RegExp(lexical.value.source, 'g')
|
||||
const assert = require('../util/assert.js')
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
export default function (liquid, Liquid) {
|
||||
const rValue = Liquid.lexical.value
|
||||
const groupRE = new RegExp(`^(?:(${rValue.source})\\s*:\\s*)?(.*)$`)
|
||||
const candidatesRE = new RegExp(rValue.source, 'g')
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('cycle', {
|
||||
|
||||
parse: function (tagToken, remainTokens) {
|
||||
@@ -12,7 +12,7 @@ module.exports = function (liquid) {
|
||||
assert(match, `illegal tag: ${tagToken.raw}`)
|
||||
|
||||
this.group = match[1] || ''
|
||||
let candidates = match[2]
|
||||
const candidates = match[2]
|
||||
|
||||
this.candidates = []
|
||||
|
||||
@@ -23,21 +23,21 @@ module.exports = function (liquid) {
|
||||
},
|
||||
|
||||
render: function (scope, hash) {
|
||||
let group = Liquid.evalValue(this.group, scope)
|
||||
let fingerprint = `cycle:${group}:` + this.candidates.join(',')
|
||||
const group = Liquid.evalValue(this.group, scope)
|
||||
const fingerprint = `cycle:${group}:` + this.candidates.join(',')
|
||||
|
||||
let groups = scope.opts.groups = scope.opts.groups || {}
|
||||
const groups = scope.opts.groups = scope.opts.groups || {}
|
||||
let idx = groups[fingerprint]
|
||||
|
||||
if (idx === undefined) {
|
||||
idx = groups[fingerprint] = 0
|
||||
}
|
||||
|
||||
let candidate = this.candidates[idx]
|
||||
const candidate = this.candidates[idx]
|
||||
idx = (idx + 1) % this.candidates.length
|
||||
groups[fingerprint] = idx
|
||||
|
||||
return Promise.resolve(Liquid.evalValue(candidate, scope))
|
||||
return Liquid.evalValue(candidate, scope)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+9
-10
@@ -1,13 +1,12 @@
|
||||
'use strict'
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const assert = require('../util/assert.js')
|
||||
const types = require('../scope').types
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
export default function (liquid, Liquid) {
|
||||
const lexical = Liquid.lexical
|
||||
const {CaptureScope, AssignScope, DecrementScope} = Liquid.Types
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('decrement', {
|
||||
parse: function (token) {
|
||||
let match = token.args.match(lexical.identifier)
|
||||
const match = token.args.match(lexical.identifier)
|
||||
assert(match, `illegal identifier ${token.args}`)
|
||||
this.variable = match[0]
|
||||
},
|
||||
@@ -15,12 +14,12 @@ module.exports = function (liquid) {
|
||||
let context = scope.findContextFor(
|
||||
this.variable,
|
||||
ctx => {
|
||||
return Object.getPrototypeOf(ctx) !== types.CaptureScope &&
|
||||
Object.getPrototypeOf(ctx) !== types.AssignScope
|
||||
return Object.getPrototypeOf(ctx) !== CaptureScope &&
|
||||
Object.getPrototypeOf(ctx) !== AssignScope
|
||||
}
|
||||
)
|
||||
if (!context) {
|
||||
context = Object.create(types.DecrementScope)
|
||||
context = Object.create(DecrementScope)
|
||||
scope.unshift(context)
|
||||
}
|
||||
if (typeof context[this.variable] !== 'number') {
|
||||
|
||||
+82
-85
@@ -1,96 +1,93 @@
|
||||
import {default as Liquid, lexical} from '../index'
|
||||
import {mapSeries} from '../util/promise.js'
|
||||
import _ from '../util/underscore.js'
|
||||
import {isString, isObject} from '../util/underscore.js'
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
const RenderBreakError = Liquid.Types.RenderBreakError
|
||||
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
|
||||
`(${lexical.value.source})` +
|
||||
`(?:\\s+${lexical.hash.source})*` +
|
||||
`(?:\\s+(reversed))?` +
|
||||
`(?:\\s+${lexical.hash.source})*$`)
|
||||
export default function (liquid, Liquid) {
|
||||
const RenderBreakError = Liquid.Types.RenderBreakError
|
||||
const lexical = Liquid.lexical
|
||||
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', {
|
||||
liquid.registerTag('for', {parse, render})
|
||||
|
||||
parse: function (tagToken, remainTokens) {
|
||||
let match = re.exec(tagToken.args)
|
||||
assert(match, `illegal tag: ${tagToken.raw}`)
|
||||
this.variable = match[1]
|
||||
this.collection = match[2]
|
||||
this.reversed = !!match[3]
|
||||
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 = []
|
||||
this.templates = []
|
||||
this.elseTemplates = []
|
||||
|
||||
let p
|
||||
let 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) {
|
||||
let 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).map((key) => [key, collection[key]])
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(collection) || !collection.length) {
|
||||
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
||||
}
|
||||
|
||||
let offset = hash.offset || 0
|
||||
let limit = (hash.limit === undefined) ? collection.length : hash.limit
|
||||
|
||||
collection = collection.slice(offset, offset + limit)
|
||||
if (this.reversed) collection.reverse()
|
||||
|
||||
let contexts = collection.map((item, i) => {
|
||||
let 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 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`)
|
||||
})
|
||||
|
||||
let 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(context))
|
||||
}).catch((e) => {
|
||||
if (e instanceof RenderBreakError && e.message === 'break') {
|
||||
return
|
||||
}
|
||||
throw e
|
||||
}).then(() => html)
|
||||
stream.start()
|
||||
}
|
||||
async function render (scope, hash) {
|
||||
let 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).map((key) => [key, collection[key]])
|
||||
}
|
||||
}
|
||||
})
|
||||
if (!Array.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
|
||||
}
|
||||
}
|
||||
|
||||
+4
-7
@@ -1,6 +1,4 @@
|
||||
import Liquid from '..'
|
||||
|
||||
module.exports = function (liquid) {
|
||||
export default function (liquid, Liquid) {
|
||||
liquid.registerTag('if', {
|
||||
|
||||
parse: function (tagToken, remainTokens) {
|
||||
@@ -8,7 +6,7 @@ module.exports = function (liquid) {
|
||||
this.elseTemplates = []
|
||||
|
||||
let p
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
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 (let i = 0; i < this.branches.length; i++) {
|
||||
let branch = this.branches[i]
|
||||
let 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)
|
||||
}
|
||||
|
||||
+28
-35
@@ -1,11 +1,11 @@
|
||||
'use strict'
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const withRE = new RegExp(`with\\s+(${lexical.value.source})`)
|
||||
const staticFileRE = /[^\s,]+/
|
||||
const assert = require('../util/assert.js')
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
const staticFileRE = /[^\s,]+/
|
||||
|
||||
export default function (liquid, Liquid) {
|
||||
const lexical = Liquid.lexical
|
||||
const withRE = new RegExp(`with\\s+(${lexical.value.source})`)
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('include', {
|
||||
parse: function (token) {
|
||||
let match = staticFileRE.exec(token.args)
|
||||
@@ -23,42 +23,35 @@ module.exports = function (liquid) {
|
||||
this.with = match[1]
|
||||
}
|
||||
},
|
||||
render: function (scope, hash) {
|
||||
let pFilepath
|
||||
render: async function (scope, hash) {
|
||||
let filepath
|
||||
if (scope.opts.dynamicPartials) {
|
||||
if (lexical.quotedLine.exec(this.value)) {
|
||||
let template = this.value.slice(1, -1)
|
||||
pFilepath = liquid.parseAndRender(template, scope.getAll(), scope.opts)
|
||||
const template = this.value.slice(1, -1)
|
||||
filepath = await liquid.parseAndRender(template, scope.getAll(), scope.opts)
|
||||
} else {
|
||||
pFilepath = Promise.resolve(Liquid.evalValue(this.value, scope))
|
||||
filepath = Liquid.evalValue(this.value, scope)
|
||||
}
|
||||
} else {
|
||||
pFilepath = Promise.resolve(this.staticValue)
|
||||
filepath = this.staticValue
|
||||
}
|
||||
assert(filepath, `cannot include with empty filename`)
|
||||
|
||||
let originBlocks = scope.opts.blocks
|
||||
let originBlockMode = scope.opts.blockMode
|
||||
const originBlocks = scope.opts.blocks
|
||||
const originBlockMode = scope.opts.blockMode
|
||||
|
||||
return pFilepath
|
||||
.then(filepath => {
|
||||
assert(filepath, `cannot include with empty filename`)
|
||||
scope.opts.blocks = {}
|
||||
scope.opts.blockMode = 'output'
|
||||
if (this.with) {
|
||||
hash[filepath] = Liquid.evalValue(this.with, scope)
|
||||
}
|
||||
return liquid.getTemplate(filepath, scope.opts.root)
|
||||
})
|
||||
.then(templates => {
|
||||
scope.push(hash)
|
||||
return liquid.renderer.renderTemplates(templates, scope)
|
||||
})
|
||||
.then((html) => {
|
||||
scope.pop(hash)
|
||||
scope.opts.blocks = originBlocks
|
||||
scope.opts.blockMode = originBlockMode
|
||||
return html
|
||||
})
|
||||
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
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+10
-10
@@ -1,12 +1,12 @@
|
||||
const Liquid = require('../index')
|
||||
const assert = require('../util/assert.js')
|
||||
const lexical = Liquid.lexical
|
||||
const types = require('../scope').types
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
export default function (liquid, Liquid) {
|
||||
const lexical = Liquid.lexical
|
||||
const {CaptureScope, AssignScope, IncrementScope} = Liquid.Types
|
||||
|
||||
module.exports = function (liquid) {
|
||||
liquid.registerTag('increment', {
|
||||
parse: function (token) {
|
||||
let match = token.args.match(lexical.identifier)
|
||||
const match = token.args.match(lexical.identifier)
|
||||
assert(match, `illegal identifier ${token.args}`)
|
||||
this.variable = match[0]
|
||||
},
|
||||
@@ -14,18 +14,18 @@ module.exports = function (liquid) {
|
||||
let context = scope.findContextFor(
|
||||
this.variable,
|
||||
ctx => {
|
||||
return Object.getPrototypeOf(ctx) !== types.CaptureScope &&
|
||||
Object.getPrototypeOf(ctx) !== types.AssignScope
|
||||
return Object.getPrototypeOf(ctx) !== CaptureScope &&
|
||||
Object.getPrototypeOf(ctx) !== AssignScope
|
||||
}
|
||||
)
|
||||
if (!context) {
|
||||
context = Object.create(types.IncrementScope)
|
||||
context = Object.create(IncrementScope)
|
||||
scope.unshift(context)
|
||||
}
|
||||
if (typeof context[this.variable] !== 'number') {
|
||||
context[this.variable] = 0
|
||||
}
|
||||
let val = context[this.variable]
|
||||
const val = context[this.variable]
|
||||
context[this.variable]++
|
||||
return val
|
||||
}
|
||||
|
||||
+30
-15
@@ -1,16 +1,31 @@
|
||||
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)
|
||||
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)
|
||||
}
|
||||
|
||||
+33
-40
@@ -1,7 +1,4 @@
|
||||
const Liquid = require('..')
|
||||
const lexical = Liquid.lexical
|
||||
const assert = require('../util/assert.js')
|
||||
const staticFileRE = /\S+/
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
/*
|
||||
* blockMode:
|
||||
@@ -9,7 +6,10 @@ const staticFileRE = /\S+/
|
||||
* * "output": output rendered html
|
||||
*/
|
||||
|
||||
module.exports = function (liquid) {
|
||||
export default function (liquid, Liquid) {
|
||||
const rValue = Liquid.lexical.value
|
||||
const staticFileRE = /\S+/
|
||||
|
||||
liquid.registerTag('layout', {
|
||||
parse: function (token, remainTokens) {
|
||||
let match = staticFileRE.exec(token.args)
|
||||
@@ -17,45 +17,41 @@ module.exports = function (liquid) {
|
||||
this.staticLayout = match[0]
|
||||
}
|
||||
|
||||
match = lexical.value.exec(token.args)
|
||||
match = rValue.exec(token.args)
|
||||
if (match) {
|
||||
this.layout = match[0]
|
||||
}
|
||||
|
||||
this.tpls = liquid.parser.parse(remainTokens)
|
||||
},
|
||||
render: function (scope, hash) {
|
||||
let layout = scope.opts.dynamicPartials ? Liquid.evalValue(this.layout, scope) : this.staticLayout
|
||||
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'
|
||||
return liquid.renderer.renderTemplates(this.tpls, scope)
|
||||
.then(html => {
|
||||
if (scope.opts.blocks[''] === undefined) {
|
||||
scope.opts.blocks[''] = html
|
||||
}
|
||||
return liquid.getTemplate(layout, scope.opts.root)
|
||||
})
|
||||
.then(templates => {
|
||||
scope.push(hash)
|
||||
scope.opts.blockMode = 'output'
|
||||
return liquid.renderer.renderTemplates(templates, scope)
|
||||
})
|
||||
.then(partial => {
|
||||
scope.pop(hash)
|
||||
return partial
|
||||
})
|
||||
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) {
|
||||
let match = /\w+/.exec(token.args)
|
||||
const match = /\w+/.exec(token.args)
|
||||
this.block = match ? match[0] : ''
|
||||
|
||||
this.tpls = []
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('tag:endblock', () => stream.stop())
|
||||
.on('template', tpl => this.tpls.push(tpl))
|
||||
.on('end', () => {
|
||||
@@ -63,20 +59,17 @@ module.exports = function (liquid) {
|
||||
})
|
||||
stream.start()
|
||||
},
|
||||
render: function (scope) {
|
||||
return Promise.resolve(scope.opts.blocks[this.block])
|
||||
.then(html => html === undefined
|
||||
// render default block
|
||||
? liquid.renderer.renderTemplates(this.tpls, scope)
|
||||
// use child-defined block
|
||||
: html)
|
||||
.then(html => {
|
||||
if (scope.opts.blockMode === 'store') {
|
||||
scope.opts.blocks[this.block] = html
|
||||
return ''
|
||||
}
|
||||
return html
|
||||
})
|
||||
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
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
module.exports = function (liquid) {
|
||||
export default function (liquid) {
|
||||
liquid.registerTag('raw', {
|
||||
parse: function (tagToken, remainTokens) {
|
||||
this.tokens = []
|
||||
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
stream
|
||||
.on('token', token => {
|
||||
if (token.name === 'endraw') stream.stop()
|
||||
|
||||
+34
-47
@@ -1,17 +1,16 @@
|
||||
import Liquid from '..'
|
||||
import {mapSeries} from '../util/promise.js'
|
||||
import assert from '../util/assert.js'
|
||||
|
||||
const lexical = Liquid.lexical
|
||||
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
|
||||
`(${lexical.value.source})` +
|
||||
`(?:\\s+${lexical.hash.source})*$`)
|
||||
export default function (liquid, Liquid) {
|
||||
const lexical = Liquid.lexical
|
||||
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) {
|
||||
let match = re.exec(tagToken.args)
|
||||
const match = re.exec(tagToken.args)
|
||||
assert(match, `illegal tag: ${tagToken.raw}`)
|
||||
|
||||
this.variable = match[1]
|
||||
@@ -19,7 +18,7 @@ module.exports = function (liquid) {
|
||||
this.templates = []
|
||||
|
||||
let p
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('start', () => (p = this.templates))
|
||||
.on('tag:endtablerow', token => stream.stop())
|
||||
.on('template', tpl => p.push(tpl))
|
||||
@@ -30,54 +29,42 @@ module.exports = function (liquid) {
|
||||
stream.start()
|
||||
},
|
||||
|
||||
render: function (scope, hash) {
|
||||
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
|
||||
|
||||
let html = ''
|
||||
let offset = hash.offset || 0
|
||||
let limit = (hash.limit === undefined) ? collection.length : hash.limit
|
||||
|
||||
let cols = hash.cols
|
||||
let row
|
||||
let col
|
||||
|
||||
// build array of arguments to pass to sequential promises...
|
||||
collection = collection.slice(offset, offset + limit)
|
||||
if (!cols) cols = collection.length
|
||||
let contexts = collection.map((item, i) => {
|
||||
let ctx = {}
|
||||
const cols = hash.cols || collection.length
|
||||
const contexts = collection.map((item, i) => {
|
||||
const ctx = {}
|
||||
ctx[this.variable] = item
|
||||
return 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) {
|
||||
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>'
|
||||
}
|
||||
return html
|
||||
})
|
||||
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
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+3
-5
@@ -1,12 +1,10 @@
|
||||
import Liquid from '../index'
|
||||
|
||||
module.exports = function (liquid) {
|
||||
export default function (liquid, Liquid) {
|
||||
liquid.registerTag('unless', {
|
||||
parse: function (tagToken, remainTokens) {
|
||||
this.templates = []
|
||||
this.elseTemplates = []
|
||||
let p
|
||||
let stream = liquid.parser.parseStream(remainTokens)
|
||||
const stream = liquid.parser.parseStream(remainTokens)
|
||||
.on('start', x => {
|
||||
p = this.templates
|
||||
this.cond = tagToken.args
|
||||
@@ -22,7 +20,7 @@ module.exports = function (liquid) {
|
||||
},
|
||||
|
||||
render: function (scope, hash) {
|
||||
let cond = Liquid.evalExp(this.cond, scope)
|
||||
const cond = Liquid.evalExp(this.cond, scope)
|
||||
return Liquid.isFalsy(cond)
|
||||
? liquid.renderer.renderTemplates(this.templates, scope)
|
||||
: liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
||||
|
||||
+15
-16
@@ -1,17 +1,19 @@
|
||||
const lexical = require('./lexical.js')
|
||||
const TokenizationError = require('./util/error.js').TokenizationError
|
||||
const _ = require('./util/underscore.js')
|
||||
const whiteSpaceCtrl = require('./whitespace-ctrl.js')
|
||||
const assert = require('./util/assert.js')
|
||||
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 (input, file, options) {
|
||||
export {default as whiteSpaceCtrl} from './whitespace-ctrl.js'
|
||||
|
||||
export function parse (input, file, options) {
|
||||
assert(_.isString(input), 'illegal input')
|
||||
|
||||
let rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
|
||||
const rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
|
||||
let currIndent = 0
|
||||
let lineNumber = LineNumber(input)
|
||||
const lineNumber = LineNumber(input)
|
||||
let lastMatchEnd = 0
|
||||
let tokens = []
|
||||
const tokens = []
|
||||
|
||||
for (let match; (match = rLiquid.exec(input)); lastMatchEnd = rLiquid.lastIndex) {
|
||||
if (match.index > lastMatchEnd) {
|
||||
@@ -28,8 +30,8 @@ function parse (input, file, options) {
|
||||
return tokens
|
||||
|
||||
function parseTagToken (raw, value, pos) {
|
||||
let match = value.match(lexical.tagLine)
|
||||
let token = {
|
||||
const match = value.match(lexical.tagLine)
|
||||
const token = {
|
||||
type: 'tag',
|
||||
indent: currIndent,
|
||||
line: lineNumber.get(pos),
|
||||
@@ -62,7 +64,7 @@ function parse (input, file, options) {
|
||||
}
|
||||
|
||||
function parseHTMLToken (begin, end) {
|
||||
let htmlFragment = input.slice(begin, end)
|
||||
const htmlFragment = input.slice(begin, end)
|
||||
currIndent = _.last((htmlFragment).split('\n')).length
|
||||
|
||||
return {
|
||||
@@ -79,13 +81,10 @@ function LineNumber (html) {
|
||||
|
||||
return {
|
||||
get: function (pos) {
|
||||
let lines = html.slice(lastMatchBegin + 1, pos).split('\n')
|
||||
const lines = html.slice(lastMatchBegin + 1, pos).split('\n')
|
||||
parsedLinesCount += lines.length - 1
|
||||
lastMatchBegin = pos
|
||||
return parsedLinesCount + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
exports.parse = parse
|
||||
exports.whiteSpaceCtrl = whiteSpaceCtrl
|
||||
|
||||
+2
-4
@@ -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
|
||||
|
||||
+9
-9
@@ -1,4 +1,4 @@
|
||||
import _ from './underscore.js'
|
||||
import * as _ from './underscore.js'
|
||||
|
||||
function initError () {
|
||||
this.name = this.constructor.name
|
||||
@@ -14,7 +14,7 @@ function initLiquidError (err, token) {
|
||||
this.line = token.line
|
||||
this.file = token.file
|
||||
|
||||
let context = mkContext(token.input, token.line)
|
||||
const context = mkContext(token.input, token.line)
|
||||
this.message = mkMessage(err.message, token)
|
||||
this.stack = context +
|
||||
'\n' + (this.stack || this.message) +
|
||||
@@ -64,11 +64,11 @@ AssertionError.prototype = Object.create(Error.prototype)
|
||||
AssertionError.prototype.constructor = AssertionError
|
||||
|
||||
function mkContext (input, line) {
|
||||
let lines = input.split('\n')
|
||||
let begin = Math.max(line - 2, 1)
|
||||
let 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)
|
||||
|
||||
let context = _
|
||||
const context = _
|
||||
.range(begin, end + 1)
|
||||
.map(l => [
|
||||
(l === line) ? '>> ' : ' ',
|
||||
@@ -82,9 +82,9 @@ function mkContext (input, line) {
|
||||
}
|
||||
|
||||
function align (n, max) {
|
||||
let length = (max + '').length
|
||||
let str = n + ''
|
||||
let blank = Array(length - str.length).join(' ')
|
||||
const length = (max + '').length
|
||||
const str = n + ''
|
||||
const blank = Array(length - str.length).join(' ')
|
||||
return blank + str
|
||||
}
|
||||
|
||||
|
||||
+3
-8
@@ -1,6 +1,6 @@
|
||||
const fs = require('fs')
|
||||
import fs from 'fs'
|
||||
|
||||
function readFileAsync (filepath) {
|
||||
export function readFileAsync (filepath) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
fs.readFile(filepath, 'utf8', function (err, content) {
|
||||
err ? reject(err) : resolve(content)
|
||||
@@ -8,13 +8,8 @@ function readFileAsync (filepath) {
|
||||
})
|
||||
};
|
||||
|
||||
function statFileAsync (path) {
|
||||
export function statFileAsync (path) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
fs.stat(path, (err, stat) => err ? reject(err) : resolve(stat))
|
||||
})
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
readFileAsync,
|
||||
statFileAsync
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
export function get (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 sending the response.'))
|
||||
}
|
||||
xhr.open('GET', url)
|
||||
xhr.send()
|
||||
})
|
||||
}
|
||||
+3
-6
@@ -4,7 +4,7 @@
|
||||
* @param {Array} iteratee returns a new promise.
|
||||
* The iteratee is invoked with three arguments: (value, index, iterable).
|
||||
*/
|
||||
function anySeries (iterable, iteratee) {
|
||||
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))
|
||||
@@ -18,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) {
|
||||
export function mapSeries (iterable, iteratee) {
|
||||
let ret = Promise.resolve('init')
|
||||
let result = []
|
||||
const result = []
|
||||
iterable.forEach(function (item, idx) {
|
||||
ret = ret
|
||||
.then(() => iteratee(item, idx, iterable))
|
||||
@@ -28,6 +28,3 @@ function mapSeries (iterable, iteratee) {
|
||||
})
|
||||
return ret.then(() => result)
|
||||
}
|
||||
|
||||
exports.anySeries = anySeries
|
||||
exports.mapSeries = mapSeries
|
||||
|
||||
+21
-23
@@ -1,16 +1,16 @@
|
||||
let monthNames = [
|
||||
const monthNames = [
|
||||
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
|
||||
'September', 'October', 'November', 'December'
|
||||
]
|
||||
let monthNamesShort = [
|
||||
const monthNamesShort = [
|
||||
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
|
||||
'Nov', 'Dec'
|
||||
]
|
||||
let dayNames = [
|
||||
const dayNames = [
|
||||
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
|
||||
]
|
||||
let dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
||||
let suffixes = {
|
||||
const dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
||||
const suffixes = {
|
||||
1: 'st',
|
||||
2: 'nd',
|
||||
3: 'rd',
|
||||
@@ -18,9 +18,9 @@ let suffixes = {
|
||||
}
|
||||
|
||||
// prototype extensions
|
||||
let _date = {
|
||||
const _date = {
|
||||
daysInMonth: function (d) {
|
||||
let 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]
|
||||
},
|
||||
|
||||
@@ -36,21 +36,21 @@ let _date = {
|
||||
// TODO: that comment was retarted. fix it.
|
||||
getWeekOfYear: function (d, startDay) {
|
||||
// Skip to startDay of this week
|
||||
let now = this.getDayOfYear(d) + (startDay - d.getDay())
|
||||
const now = this.getDayOfYear(d) + (startDay - d.getDay())
|
||||
// Find the first startDay of the year
|
||||
let jan1 = new Date(d.getFullYear(), 0, 1)
|
||||
let 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) {
|
||||
let year = d.getFullYear()
|
||||
const year = d.getFullYear()
|
||||
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)))
|
||||
},
|
||||
|
||||
getSuffix: function (d) {
|
||||
let str = d.getDate().toString()
|
||||
let index = parseInt(str.slice(-1))
|
||||
const str = d.getDate().toString()
|
||||
const index = parseInt(str.slice(-1))
|
||||
return suffixes[index] || suffixes['default']
|
||||
},
|
||||
|
||||
@@ -59,7 +59,7 @@ let _date = {
|
||||
}
|
||||
}
|
||||
|
||||
let _number = {
|
||||
const _number = {
|
||||
pad: function (value, size, ch) {
|
||||
if (!ch) ch = '0'
|
||||
let result = value.toString()
|
||||
@@ -73,7 +73,7 @@ let _number = {
|
||||
}
|
||||
}
|
||||
|
||||
let formatCodes = {
|
||||
const formatCodes = {
|
||||
a: function (d) {
|
||||
return dayNamesShort[d.getDay()]
|
||||
},
|
||||
@@ -162,7 +162,7 @@ let formatCodes = {
|
||||
return d.getFullYear()
|
||||
},
|
||||
z: function (d) {
|
||||
let tz = d.getTimezoneOffset() / 60 * 100
|
||||
const tz = d.getTimezoneOffset() / 60 * 100
|
||||
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4)
|
||||
},
|
||||
'%': function () {
|
||||
@@ -172,13 +172,13 @@ let formatCodes = {
|
||||
formatCodes.h = formatCodes.b
|
||||
formatCodes.N = formatCodes.L
|
||||
|
||||
let strftime = function (d, format) {
|
||||
export default function (d, format) {
|
||||
let output = ''
|
||||
let remaining = format
|
||||
|
||||
while (true) {
|
||||
let r = /%./g
|
||||
let results = r.exec(remaining)
|
||||
const r = /%./g
|
||||
const results = r.exec(remaining)
|
||||
|
||||
// No more format codes. Add the remaining text and return
|
||||
if (!results) {
|
||||
@@ -190,10 +190,8 @@ let strftime = function (d, format) {
|
||||
remaining = remaining.slice(r.lastIndex)
|
||||
|
||||
// Add the format code
|
||||
let ch = results[0].charAt(1)
|
||||
let func = formatCodes[ch]
|
||||
const ch = results[0].charAt(1)
|
||||
const func = formatCodes[ch]
|
||||
output += func ? func.call(this, d) : '%' + ch
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = strftime
|
||||
|
||||
+19
-36
@@ -5,11 +5,11 @@ 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) {
|
||||
export function isString (value) {
|
||||
return toStr.call(value) === '[object String]'
|
||||
}
|
||||
|
||||
function stringify (value) {
|
||||
export function stringify (value) {
|
||||
if (isNil(value)) {
|
||||
return String(value)
|
||||
}
|
||||
@@ -23,7 +23,7 @@ function stringify (value) {
|
||||
return value
|
||||
}
|
||||
|
||||
let cache = []
|
||||
const cache = []
|
||||
return JSON.stringify(value, (key, value) => {
|
||||
if (isObject(value)) {
|
||||
if (cache.indexOf(value) !== -1) {
|
||||
@@ -35,17 +35,17 @@ function stringify (value) {
|
||||
})
|
||||
}
|
||||
|
||||
function isNil (value) {
|
||||
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) {
|
||||
let signature = Object.prototype.toString.call(value)
|
||||
export function isError (value) {
|
||||
const signature = Object.prototype.toString.call(value)
|
||||
// [object XXXError]
|
||||
return signature.substr(-6, 5) === 'Error' ||
|
||||
(typeof value.message === 'string' && typeof value.name === 'string')
|
||||
@@ -59,9 +59,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 (let k in object) {
|
||||
for (const k in object) {
|
||||
if (object.hasOwnProperty(k)) {
|
||||
if (iteratee(object[k], k, object) === false) break
|
||||
}
|
||||
@@ -80,20 +80,20 @@ 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 : {}
|
||||
let srcs = Array.prototype.slice.call(arguments, 1)
|
||||
const srcs = Array.prototype.slice.call(arguments, 1)
|
||||
srcs.forEach((src) => Object.assign(object, src))
|
||||
return object
|
||||
}
|
||||
|
||||
function last (arr) {
|
||||
export function last (arr) {
|
||||
return arr[arr.length - 1]
|
||||
}
|
||||
|
||||
function uniq (arr) {
|
||||
let u = {}
|
||||
let a = []
|
||||
export function uniq (arr) {
|
||||
const u = {}
|
||||
const a = []
|
||||
for (let i = 0, l = arr.length; i < l; ++i) {
|
||||
if (u.hasOwnProperty(arr[i])) {
|
||||
continue
|
||||
@@ -110,8 +110,8 @@ function uniq (arr) {
|
||||
* @param {any} value The value to check.
|
||||
* @return {Boolean} Returns true if value is an object, else false.
|
||||
*/
|
||||
function isObject (value) {
|
||||
let type = typeof value
|
||||
export function isObject (value) {
|
||||
const type = typeof value
|
||||
return value != null && (type === 'object' || type === 'function')
|
||||
}
|
||||
|
||||
@@ -123,33 +123,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
|
||||
|
||||
let arr = []
|
||||
const arr = []
|
||||
for (let i = start; i < stop; i += step) {
|
||||
arr.push(i)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
// lang
|
||||
exports.isString = isString
|
||||
exports.isObject = isObject
|
||||
exports.isArray = isArray
|
||||
exports.isNil = isNil
|
||||
exports.isError = isError
|
||||
|
||||
// array
|
||||
exports.range = range
|
||||
exports.last = last
|
||||
|
||||
// object
|
||||
exports.forOwn = forOwn
|
||||
exports.assign = assign
|
||||
exports.uniq = uniq
|
||||
exports.stringify = stringify
|
||||
|
||||
+20
-4
@@ -1,5 +1,4 @@
|
||||
import resolveUrl from 'resolve-url'
|
||||
import _ from './underscore'
|
||||
import {last, isArray} from './underscore'
|
||||
|
||||
const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/
|
||||
const urlRe = /^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[:?\d]*)\S*$/
|
||||
@@ -15,11 +14,28 @@ export function valid (path) {
|
||||
}
|
||||
|
||||
export function resolve (root, path) {
|
||||
if (Object.prototype.toString.call(root) === '[object Array]') {
|
||||
if (isArray(root)) {
|
||||
root = root[0]
|
||||
}
|
||||
if (root && _.last(root) !== '/') {
|
||||
if (root && last(root) !== '/') {
|
||||
root += '/'
|
||||
}
|
||||
return resolveUrl(root, path)
|
||||
}
|
||||
|
||||
function resolveUrl (root, path) {
|
||||
const base = document.createElement('base')
|
||||
base.href = arguments[0]
|
||||
|
||||
const head = document.getElementsByTagName('head')[0]
|
||||
head.insertBefore(base, head.firstChild)
|
||||
|
||||
const a = document.createElement('a')
|
||||
a.href = path
|
||||
const resolved = a.href
|
||||
base.href = resolved
|
||||
|
||||
head.removeChild(base)
|
||||
|
||||
return resolved
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const _ = require('./util/underscore.js')
|
||||
import {assign} from './util/underscore.js'
|
||||
|
||||
function whiteSpaceCtrl (tokens, options) {
|
||||
options = _.assign({ greedy: true }, options)
|
||||
export default function whiteSpaceCtrl (tokens, options) {
|
||||
options = assign({ greedy: true }, options)
|
||||
let inRaw = false
|
||||
|
||||
tokens.forEach((token, i) => {
|
||||
@@ -33,15 +33,13 @@ function shouldTrimRight (token, inRaw, options) {
|
||||
function trimLeft (token, greedy) {
|
||||
if (!token || token.type !== 'html') return
|
||||
|
||||
let rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
|
||||
const rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
|
||||
token.value = token.value.replace(rLeft, '')
|
||||
}
|
||||
|
||||
function trimRight (token, greedy) {
|
||||
if (!token || token.type !== 'html') return
|
||||
|
||||
let rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
|
||||
const rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
|
||||
token.value = token.value.replace(rRight, '')
|
||||
}
|
||||
|
||||
module.exports = whiteSpaceCtrl
|
||||
|
||||
+12
-9
@@ -1,9 +1,12 @@
|
||||
const chai = require('chai')
|
||||
import chai from 'chai'
|
||||
import request from 'supertest'
|
||||
import express from 'express'
|
||||
import mock from 'mock-fs'
|
||||
import Liquid from '../src'
|
||||
import chaiAsPromised from 'chai-as-promised'
|
||||
|
||||
const expect = chai.expect
|
||||
const mock = require('mock-fs')
|
||||
const request = require('supertest')
|
||||
const express = require('express')
|
||||
const Liquid = require('../src')
|
||||
chai.use(chaiAsPromised)
|
||||
|
||||
describe('engine#express()', function () {
|
||||
let app, engine
|
||||
@@ -36,11 +39,11 @@ describe('engine#express()', function () {
|
||||
.expect(200, done)
|
||||
})
|
||||
it('should pass error when file not found', function (done) {
|
||||
let view = {
|
||||
const view = {
|
||||
root: []
|
||||
}
|
||||
let file = '/not-exist.html'
|
||||
let 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) {
|
||||
let files = {}
|
||||
const files = {}
|
||||
files[process.cwd() + '/views/include.html'] = '{% include file %}'
|
||||
files[process.cwd() + '/views/bar.html'] = 'bar'
|
||||
mock(files)
|
||||
|
||||
+16
-16
@@ -1,21 +1,21 @@
|
||||
const chai = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const sinonChai = require('sinon-chai')
|
||||
const expect = chai.expect
|
||||
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)
|
||||
|
||||
let filter = require('../src/filter.js')()
|
||||
let Scope = require('../src/scope.js')
|
||||
const expect = chai.expect
|
||||
const filter = Filter()
|
||||
|
||||
describe('filter', function () {
|
||||
let scope
|
||||
beforeEach(function () {
|
||||
filter.clear()
|
||||
scope = Scope.factory()
|
||||
scope = scopeFactory()
|
||||
})
|
||||
it('should return default filter when not registered', function () {
|
||||
let result = filter.construct('foo')
|
||||
const result = filter.construct('foo')
|
||||
expect(result.name).to.equal('foo')
|
||||
})
|
||||
|
||||
@@ -27,7 +27,7 @@ describe('filter', function () {
|
||||
|
||||
it('should parse argument syntax', function () {
|
||||
filter.register('foo', x => x)
|
||||
let f = filter.construct('foo: a, "b"')
|
||||
const f = filter.construct('foo: a, "b"')
|
||||
|
||||
expect(f.name).to.equal('foo')
|
||||
expect(f.args).to.deep.equal(['a', '"b"'])
|
||||
@@ -49,7 +49,7 @@ describe('filter', function () {
|
||||
})
|
||||
|
||||
it('should call filter with corrct arguments', function () {
|
||||
let spy = sinon.spy()
|
||||
const spy = sinon.spy()
|
||||
filter.register('foo', spy)
|
||||
filter.construct('foo: 33').render('foo', scope)
|
||||
expect(spy).to.have.been.calledWith('foo', 33)
|
||||
@@ -57,35 +57,35 @@ describe('filter', function () {
|
||||
|
||||
it('should support arguments as named key/values', function () {
|
||||
filter.register('foo', x => x)
|
||||
let f = filter.construct('foo: key1: "literal1", key2: value2')
|
||||
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)
|
||||
let f = filter.construct('foo: "test0", key1: "literal1", key2: value2')
|
||||
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)
|
||||
let f = filter.construct('foo: test0, key1: "literal1", key2: value2')
|
||||
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)
|
||||
let f = filter.construct('foo: a: a')
|
||||
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)
|
||||
let f = filter.construct('foo: a: "a"')
|
||||
const f = filter.construct('foo: a: "a"')
|
||||
expect(f.name).to.equal('foo')
|
||||
expect(f.args).to.deep.equal(['\'a\'', '"a"'])
|
||||
})
|
||||
|
||||
+8
-8
@@ -6,7 +6,7 @@ chai.use(chaiAsPromised)
|
||||
const liquid = new Liquid()
|
||||
const expect = chai.expect
|
||||
|
||||
let ctx = {
|
||||
const ctx = {
|
||||
date: new Date(),
|
||||
foo: 'bar',
|
||||
arr: [-2, 'a'],
|
||||
@@ -85,7 +85,7 @@ describe('filters', function () {
|
||||
|
||||
describe('date', function () {
|
||||
it('should support date: %a %b %d %Y', function () {
|
||||
let 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 () {
|
||||
@@ -142,7 +142,7 @@ describe('filters', function () {
|
||||
})
|
||||
|
||||
it('should support split/first', function () {
|
||||
let src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
|
||||
const src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
|
||||
'{{ my_array | first }}'
|
||||
return test(src, 'apples')
|
||||
})
|
||||
@@ -155,19 +155,19 @@ describe('filters', function () {
|
||||
})
|
||||
|
||||
it('should support join', function () {
|
||||
let src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
|
||||
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 () {
|
||||
let src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
|
||||
const src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
|
||||
'{{ my_array|last }}'
|
||||
return test(src, 'tiger')
|
||||
})
|
||||
|
||||
it('should support lstrip', function () {
|
||||
let src = '{{ " So much room for activities! " | lstrip }}'
|
||||
const src = '{{ " So much room for activities! " | lstrip }}'
|
||||
return test(src, 'So much room for activities! ')
|
||||
})
|
||||
|
||||
@@ -193,12 +193,12 @@ describe('filters', function () {
|
||||
})
|
||||
|
||||
it('should support string_with_newlines', function () {
|
||||
let src = '{% capture string_with_newlines %}\n' +
|
||||
const src = '{% capture string_with_newlines %}\n' +
|
||||
'Hello\n' +
|
||||
'there\n' +
|
||||
'{% endcapture %}' +
|
||||
'{{ string_with_newlines | newline_to_br }}'
|
||||
let dst = '<br />' +
|
||||
const dst = '<br />' +
|
||||
'Hello<br />' +
|
||||
'there<br />'
|
||||
return test(src, dst)
|
||||
|
||||
+12
-10
@@ -1,8 +1,10 @@
|
||||
const chai = require('chai')
|
||||
import chai from 'chai'
|
||||
import mock from 'mock-fs'
|
||||
import Liquid from '../src'
|
||||
import chaiAsPromised from 'chai-as-promised'
|
||||
|
||||
const expect = chai.expect
|
||||
const Liquid = require('../src')
|
||||
const mock = require('mock-fs')
|
||||
chai.use(require('chai-as-promised'))
|
||||
chai.use(chaiAsPromised)
|
||||
|
||||
describe('liquid', function () {
|
||||
let engine, strictEngine, ctx
|
||||
@@ -37,7 +39,7 @@ describe('liquid', function () {
|
||||
})
|
||||
describe('Liquid', function () {
|
||||
it('should ignore invalid root option', function () {
|
||||
let liquid = Liquid({ root: /regex/ })
|
||||
const liquid = Liquid({ root: /regex/ })
|
||||
expect(liquid.options.root).to.deep.equal([])
|
||||
})
|
||||
})
|
||||
@@ -68,18 +70,18 @@ describe('liquid', function () {
|
||||
}).to.not.throw()
|
||||
})
|
||||
it('should render template multiple times', function () {
|
||||
let template = engine.parse('{{obj}}')
|
||||
const 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 () {
|
||||
let template = engine.parse('<p>{{arr | join: "_"}}</p>')
|
||||
const 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 () {
|
||||
let src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
|
||||
const src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
|
||||
'{{ my_array | first }}'
|
||||
return expect(engine.parseAndRender(src)).to.eventually.equal('apples')
|
||||
})
|
||||
@@ -89,7 +91,7 @@ describe('liquid', function () {
|
||||
.to.eventually.equal('foo')
|
||||
})
|
||||
it('should find files without extname', function () {
|
||||
let engine = Liquid({root: '/root'})
|
||||
const engine = Liquid({root: '/root'})
|
||||
return expect(engine.renderFile('/root/files/bar', ctx))
|
||||
.to.eventually.equal('bar')
|
||||
})
|
||||
@@ -106,7 +108,7 @@ describe('liquid', function () {
|
||||
.to.eventually.equal('foo')
|
||||
})
|
||||
it('should default root to cwd', function () {
|
||||
let files = {}
|
||||
const files = {}
|
||||
files[process.cwd() + '/foo.html'] = 'FOO'
|
||||
mock(files)
|
||||
|
||||
|
||||
+6
-6
@@ -1,7 +1,7 @@
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
|
||||
let 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 () {
|
||||
let 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 () {
|
||||
let 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 () {
|
||||
let 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 () {
|
||||
let 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 () {
|
||||
let match = lexical.matchValue('var-1')
|
||||
const match = lexical.matchValue('var-1')
|
||||
expect(match && match[0]).to.equal('var-1')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
const chai = require('chai')
|
||||
import chai from 'chai'
|
||||
import mock from 'mock-fs'
|
||||
import Liquid from '../../src'
|
||||
import chaiAsPromised from 'chai-as-promised'
|
||||
|
||||
const expect = chai.expect
|
||||
const mock = require('mock-fs')
|
||||
const Liquid = require('../../src')
|
||||
chai.use(require('chai-as-promised'))
|
||||
chai.use(chaiAsPromised)
|
||||
|
||||
describe('cache options', function () {
|
||||
let engine
|
||||
|
||||
@@ -6,7 +6,7 @@ chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('strict options', function () {
|
||||
let engine
|
||||
let ctx = {}
|
||||
const ctx = {}
|
||||
beforeEach(function () {
|
||||
engine = Liquid({
|
||||
root: '/root/',
|
||||
@@ -18,16 +18,16 @@ describe('strict options', function () {
|
||||
.eventually.equal('beforeafter')
|
||||
})
|
||||
it('should throw when strict_variables true', function () {
|
||||
let tpl = engine.parse('before{{notdefined}}after')
|
||||
let opts = {
|
||||
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 () {
|
||||
let html = 'before{{notdefined}}after'
|
||||
let opts = {
|
||||
const html = 'before{{notdefined}}after'
|
||||
const opts = {
|
||||
strict_variables: true
|
||||
}
|
||||
return expect(engine.parseAndRender(html, ctx, opts)).to
|
||||
|
||||
+21
-19
@@ -1,62 +1,64 @@
|
||||
const chai = require('chai')
|
||||
import chai from 'chai'
|
||||
import Liquid from '../../src'
|
||||
import chaiAsPromised from 'chai-as-promised'
|
||||
|
||||
const expect = chai.expect
|
||||
const Liquid = require('../../src')
|
||||
chai.use(require('chai-as-promised'))
|
||||
chai.use(chaiAsPromised)
|
||||
|
||||
describe('trimming', function () {
|
||||
let ctx = {name: 'harttle'}
|
||||
const ctx = {name: 'harttle'}
|
||||
|
||||
describe('tag trimming', function () {
|
||||
it('should respect trim_tag_left', function () {
|
||||
let engine = Liquid({ trim_tag_left: true })
|
||||
const engine = Liquid({ trim_tag_left: true })
|
||||
return expect(engine.parseAndRender(' \n \t{%if true%}foo{%endif%} '))
|
||||
.to.eventually.equal('foo ')
|
||||
})
|
||||
it('should respect trim_tag_right', function () {
|
||||
let engine = Liquid({ trim_tag_right: true })
|
||||
const engine = Liquid({ trim_tag_right: true })
|
||||
return expect(engine.parseAndRender('\t{%if true%}foo{%endif%} \n'))
|
||||
.to.eventually.equal('\tfoo')
|
||||
})
|
||||
it('should not trim value', function () {
|
||||
let engine = Liquid({ trim_tag_left: true, trim_tag_right: true })
|
||||
const engine = Liquid({ trim_tag_left: true, trim_tag_right: true })
|
||||
return expect(engine.parseAndRender('{%if true%}a {{name}} b{%endif%}', ctx))
|
||||
.to.eventually.equal('a harttle b')
|
||||
})
|
||||
})
|
||||
describe('value trimming', function () {
|
||||
it('should respect trim_value_left', function () {
|
||||
let engine = Liquid({ trim_value_left: true })
|
||||
const engine = Liquid({ trim_value_left: true })
|
||||
return expect(engine.parseAndRender(' \n \t{{name}} ', ctx))
|
||||
.to.eventually.equal('harttle ')
|
||||
})
|
||||
it('should respect trim_value_right', function () {
|
||||
let engine = Liquid({ trim_value_right: true })
|
||||
const engine = Liquid({ trim_value_right: true })
|
||||
return expect(engine.parseAndRender(' \n \t{{name}} ', ctx))
|
||||
.to.eventually.equal(' \n \tharttle')
|
||||
})
|
||||
it('should respect not trim tag', function () {
|
||||
let engine = Liquid({ trim_value_left: true, trim_value_right: true })
|
||||
const engine = Liquid({ trim_value_left: true, trim_value_right: true })
|
||||
return expect(engine.parseAndRender('\t{% if true %} aha {%endif%}\t'))
|
||||
.to.eventually.equal('\t aha \t')
|
||||
})
|
||||
})
|
||||
describe('greedy', function () {
|
||||
let src = '\n {%-if true-%}\n a \n{{-name-}}{%-endif-%}\n '
|
||||
const src = '\n {%-if true-%}\n a \n{{-name-}}{%-endif-%}\n '
|
||||
it('should enable greedy by default', function () {
|
||||
let engine = Liquid()
|
||||
const engine = Liquid()
|
||||
return expect(engine.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('aharttle')
|
||||
})
|
||||
it('should respect to greedy:false by default', function () {
|
||||
let engine = Liquid({greedy: false})
|
||||
const engine = Liquid({greedy: false})
|
||||
return expect(engine.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('\n a \nharttle ')
|
||||
})
|
||||
})
|
||||
describe('markup', function () {
|
||||
it('should support trim using markup', function () {
|
||||
let engine = Liquid()
|
||||
let src = [
|
||||
const engine = Liquid()
|
||||
const src = [
|
||||
'{%- assign username = "John G. Chalmers-Smith" -%}',
|
||||
'{%- if username and username.length > 10 -%}',
|
||||
' Wow, {{ username }}, you have a long name!',
|
||||
@@ -64,12 +66,12 @@ describe('trimming', function () {
|
||||
' Hello there!',
|
||||
'{%- endif -%}'
|
||||
].join('\n')
|
||||
let dst = 'Wow, John G. Chalmers-Smith, you have a long name!'
|
||||
const dst = 'Wow, John G. Chalmers-Smith, you have a long name!'
|
||||
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
it('should not trim when not specified', function () {
|
||||
let engine = Liquid()
|
||||
let src = [
|
||||
const engine = Liquid()
|
||||
const src = [
|
||||
'{% assign username = "John G. Chalmers-Smith" %}',
|
||||
'{% if username and username.length > 10 %}',
|
||||
' Wow, {{ username }}, you have a long name!',
|
||||
@@ -77,7 +79,7 @@ describe('trimming', function () {
|
||||
' Hello there!',
|
||||
'{% endif %}'
|
||||
].join('\n')
|
||||
let dst = '\n\n Wow, John G. Chalmers-Smith, you have a long name!\n'
|
||||
const dst = '\n\n Wow, John G. Chalmers-Smith, you have a long name!\n'
|
||||
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
})
|
||||
|
||||
+13
-11
@@ -1,15 +1,17 @@
|
||||
const chai = require('chai')
|
||||
import chai from 'chai'
|
||||
import sinonChai from 'sinon-chai'
|
||||
import Filter from '../src/filter.js'
|
||||
import Tag from '../src/tag.js'
|
||||
import Template from '../src/parser.js'
|
||||
|
||||
const expect = chai.expect
|
||||
|
||||
chai.use(require('sinon-chai'))
|
||||
|
||||
let filter = require('../src/filter.js')()
|
||||
let tag = require('../src/tag.js')()
|
||||
let Template = require('../src/parser.js')
|
||||
const filter = Filter()
|
||||
const tag = Tag()
|
||||
chai.use(sinonChai)
|
||||
|
||||
describe('template', function () {
|
||||
let template
|
||||
let add = (l, r) => l + r
|
||||
const add = (l, r) => l + r
|
||||
|
||||
beforeEach(function () {
|
||||
filter.clear()
|
||||
@@ -26,21 +28,21 @@ describe('template', function () {
|
||||
})
|
||||
|
||||
it('should parse value string', function () {
|
||||
let tpl = template.parseValue('foo')
|
||||
const tpl = template.parseValue('foo')
|
||||
expect(tpl.type).to.equal('value')
|
||||
expect(tpl.initial).to.equal('foo')
|
||||
expect(tpl.filters).to.deep.equal([])
|
||||
})
|
||||
|
||||
it('should parse value string with a simple filter', function () {
|
||||
let tpl = template.parseValue('foo | add: 3, "foo"')
|
||||
const tpl = template.parseValue('foo | add: 3, "foo"')
|
||||
expect(tpl.initial).to.equal('foo')
|
||||
expect(tpl.filters.length).to.equal(1)
|
||||
expect(tpl.filters[0].filter).to.equal(add)
|
||||
})
|
||||
|
||||
it('should parse value string with filters', function () {
|
||||
let tpl = template.parseValue('foo | add: "|" | add')
|
||||
const tpl = template.parseValue('foo | add: "|" | add')
|
||||
expect(tpl.initial).to.equal('foo')
|
||||
expect(tpl.filters.length).to.equal(2)
|
||||
})
|
||||
|
||||
+32
-32
@@ -1,18 +1,20 @@
|
||||
'use strict'
|
||||
const chai = require('chai')
|
||||
const chaiAsPromised = require('chai-as-promised')
|
||||
const expect = chai.expect
|
||||
const sinonChai = require('sinon-chai')
|
||||
const sinon = require('sinon')
|
||||
import chai from 'chai'
|
||||
import chaiAsPromised from 'chai-as-promised'
|
||||
import sinonChai from 'sinon-chai'
|
||||
import sinon from 'sinon'
|
||||
import Tag from '../src/tag.js'
|
||||
import {factory as scopeFactory} from '../src/scope.js'
|
||||
import Filter from '../src/filter'
|
||||
import Render from '../src/render.js'
|
||||
import parser from '../src/parser.js'
|
||||
|
||||
chai.use(sinonChai)
|
||||
chai.use(chaiAsPromised)
|
||||
|
||||
let tag = require('../src/tag.js')()
|
||||
let Scope = require('../src/scope.js')
|
||||
let filter = require('../src/filter')()
|
||||
let Render = require('../src/render.js')
|
||||
let Template = require('../src/parser.js')(tag, filter)
|
||||
const expect = chai.expect
|
||||
const tag = Tag()
|
||||
const filter = Filter()
|
||||
const Template = parser(tag, filter)
|
||||
let render
|
||||
|
||||
describe('render', function () {
|
||||
@@ -24,43 +26,41 @@ describe('render', function () {
|
||||
|
||||
describe('.renderTemplates()', function () {
|
||||
it('should throw when scope undefined', function () {
|
||||
expect(function () {
|
||||
render.renderTemplates([])
|
||||
}).to.throw(/scope undefined/)
|
||||
expect(render.renderTemplates([])).to.be.rejectedWith(/scope undefined/)
|
||||
})
|
||||
|
||||
it('should render html', function () {
|
||||
let scope = Scope.factory({})
|
||||
const scope = scopeFactory({})
|
||||
return expect(render.renderTemplates([{type: 'html', value: '<p>'}], scope)).to.eventually.equal('<p>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('.renderValue()', function () {
|
||||
it('should respect to .to_liquid() method', function () {
|
||||
let scope = Scope.factory({
|
||||
const scope = scopeFactory({
|
||||
bar: { to_liquid: x => 'custom' }
|
||||
})
|
||||
let tpl = Template.parseValue('bar')
|
||||
const tpl = Template.parseValue('bar')
|
||||
return expect(render.renderValue(tpl, scope)).to.eventually.equal('custom')
|
||||
})
|
||||
it('should stringify objects', function () {
|
||||
let scope = Scope.factory({
|
||||
const scope = scopeFactory({
|
||||
foo: { obj: { arr: ['a', 2] } }
|
||||
})
|
||||
let tpl = Template.parseValue('foo')
|
||||
const tpl = Template.parseValue('foo')
|
||||
return expect(render.renderValue(tpl, scope)).to.eventually.equal('{"obj":{"arr":["a",2]}}')
|
||||
})
|
||||
it('should skip circular property', function () {
|
||||
let ctx = { foo: { num: 2 }, bar: 'bar' }
|
||||
const ctx = { foo: { num: 2 }, bar: 'bar' }
|
||||
ctx.foo.circular = ctx
|
||||
|
||||
let scope = Scope.factory(ctx)
|
||||
let tpl = Template.parseValue('foo')
|
||||
const scope = scopeFactory(ctx)
|
||||
const tpl = Template.parseValue('foo')
|
||||
return expect(render.renderValue(tpl, scope)).to.eventually.equal('{"num":2,"circular":{"bar":"bar"}}')
|
||||
})
|
||||
it('should skip function property', function () {
|
||||
let scope = Scope.factory({obj: {foo: 'foo', bar: x => x}})
|
||||
let tpl = Template.parseValue('obj')
|
||||
const scope = scopeFactory({obj: {foo: 'foo', bar: x => x}})
|
||||
const tpl = Template.parseValue('obj')
|
||||
return expect(render.renderValue(tpl, scope)).to.eventually.equal('{"foo":"foo"}')
|
||||
})
|
||||
})
|
||||
@@ -74,24 +74,24 @@ describe('render', function () {
|
||||
it('should eval value', function () {
|
||||
filter.register('date', (l, r) => l + r)
|
||||
filter.register('time', (l, r) => l + 3 * r)
|
||||
let tpl = Template.parseValue('foo.bar[0] | date: "b" | time:2')
|
||||
let scope = Scope.factory({
|
||||
const tpl = Template.parseValue('foo.bar[0] | date: "b" | time:2')
|
||||
const scope = scopeFactory({
|
||||
foo: { bar: ['a'] }
|
||||
})
|
||||
expect(render.evalValue(tpl, scope)).to.equal('ab6')
|
||||
})
|
||||
it('should reserve type', function () {
|
||||
filter.register('arr', () => [1])
|
||||
let tpl = Template.parseValue('"x" | arr')
|
||||
expect(render.evalValue(tpl, Scope.factory())).to.deep.equal([1])
|
||||
const tpl = Template.parseValue('"x" | arr')
|
||||
expect(render.evalValue(tpl, scopeFactory())).to.deep.equal([1])
|
||||
})
|
||||
it('should eval filter with correct arguments', function () {
|
||||
let date = sinon.stub().returns('y')
|
||||
let time = sinon.spy()
|
||||
const date = sinon.stub().returns('y')
|
||||
const time = sinon.spy()
|
||||
filter.register('date', date)
|
||||
filter.register('time', time)
|
||||
let tpl = Template.parseValue('foo.bar | date: "b" | time:2')
|
||||
let scope = Scope.factory({
|
||||
const tpl = Template.parseValue('foo.bar | date: "b" | time:2')
|
||||
const scope = scopeFactory({
|
||||
foo: {bar: 'bar'}
|
||||
})
|
||||
render.evalValue(tpl, scope)
|
||||
|
||||
+8
-8
@@ -1,5 +1,5 @@
|
||||
import chai from 'chai'
|
||||
import Scope from '../src/scope.js'
|
||||
import {factory as scopeFactory} from '../src/scope.js'
|
||||
|
||||
const expect = chai.expect
|
||||
|
||||
@@ -14,7 +14,7 @@ describe('scope', function () {
|
||||
arr: ['a', 'b']
|
||||
}
|
||||
}
|
||||
scope = Scope.factory(ctx)
|
||||
scope = scopeFactory(ctx)
|
||||
})
|
||||
|
||||
describe('#propertyAccessSeq()', function () {
|
||||
@@ -88,7 +88,7 @@ describe('scope', function () {
|
||||
})
|
||||
|
||||
it('should respect to to_liquid', function () {
|
||||
let scope = Scope.factory({foo: {
|
||||
const scope = scopeFactory({foo: {
|
||||
to_liquid: () => ({bar: 'BAR'}),
|
||||
bar: 'bar'
|
||||
}})
|
||||
@@ -96,7 +96,7 @@ describe('scope', function () {
|
||||
})
|
||||
|
||||
it('should respect to toLiquid', function () {
|
||||
let scope = Scope.factory({foo: {
|
||||
const scope = scopeFactory({foo: {
|
||||
toLiquid: () => ({bar: 'BAR'}),
|
||||
bar: 'bar'
|
||||
}})
|
||||
@@ -162,7 +162,7 @@ describe('scope', function () {
|
||||
describe('strict_variables', function () {
|
||||
let scope
|
||||
beforeEach(function () {
|
||||
scope = Scope.factory(ctx, {
|
||||
scope = scopeFactory(ctx, {
|
||||
strict_variables: true
|
||||
})
|
||||
})
|
||||
@@ -227,10 +227,10 @@ describe('scope', function () {
|
||||
})
|
||||
})
|
||||
it('should pop specified scope', function () {
|
||||
let scope1 = {
|
||||
const scope1 = {
|
||||
foo: 'foo'
|
||||
}
|
||||
let scope2 = {
|
||||
const scope2 = {
|
||||
bar: 'bar'
|
||||
}
|
||||
scope.push(scope1)
|
||||
@@ -242,7 +242,7 @@ describe('scope', function () {
|
||||
expect(scope.get('bar')).to.equal('bar')
|
||||
})
|
||||
it('should throw when specified scope not found', function () {
|
||||
let scope1 = {
|
||||
const scope1 = {
|
||||
foo: 'foo'
|
||||
}
|
||||
expect(() => scope.pop(scope1)).to.throw('scope not found, cannot pop')
|
||||
|
||||
+6
-6
@@ -1,11 +1,11 @@
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
let syntax = require('../src/syntax.js')
|
||||
let Scope = require('../src/scope.js')
|
||||
const syntax = require('../src/syntax.js')
|
||||
const Scope = require('../src/scope.js')
|
||||
|
||||
let evalExp = syntax.evalExp
|
||||
let evalValue = syntax.evalValue
|
||||
let isTruthy = syntax.isTruthy
|
||||
const evalExp = syntax.evalExp
|
||||
const evalValue = syntax.evalValue
|
||||
const isTruthy = syntax.isTruthy
|
||||
|
||||
describe('expression', function () {
|
||||
let scope
|
||||
@@ -36,7 +36,7 @@ describe('expression', function () {
|
||||
})
|
||||
|
||||
it('should throw if not valid', function () {
|
||||
let fn = () => evalValue('===')
|
||||
const fn = () => evalValue('===')
|
||||
expect(fn).to.throw("cannot eval '===' as value")
|
||||
})
|
||||
})
|
||||
|
||||
+41
-40
@@ -1,15 +1,17 @@
|
||||
const chai = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const expect = chai.expect
|
||||
chai.use(require('sinon-chai'))
|
||||
import chai from 'chai'
|
||||
import Tag from '../src/tag.js'
|
||||
import {factory as scopeFactory} from '../src/scope.js'
|
||||
import sinon from 'sinon'
|
||||
import sinonChai from 'sinon-chai'
|
||||
|
||||
let tag = require('../src/tag.js')()
|
||||
let Scope = require('../src/scope.js')
|
||||
chai.use(sinonChai)
|
||||
const expect = chai.expect
|
||||
const tag = Tag()
|
||||
|
||||
describe('tag', function () {
|
||||
let scope
|
||||
before(function () {
|
||||
scope = Scope.factory({
|
||||
scope = scopeFactory({
|
||||
foo: 'bar',
|
||||
arr: [2, 1],
|
||||
bar: {
|
||||
@@ -37,19 +39,18 @@ describe('tag', function () {
|
||||
}).not.throw()
|
||||
})
|
||||
|
||||
it('should call tag.render', function () {
|
||||
let spy = sinon.spy()
|
||||
it('should call tag.render', async function () {
|
||||
const 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)
|
||||
const token = {
|
||||
type: 'tag',
|
||||
value: 'foo',
|
||||
name: 'foo'
|
||||
}
|
||||
await tag.construct(token, []).render(scope, {})
|
||||
expect(spy).to.have.been.called
|
||||
})
|
||||
|
||||
describe('hash', function () {
|
||||
@@ -66,33 +67,33 @@ describe('tag', function () {
|
||||
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 call tag.render with scope', async function () {
|
||||
await tag.construct(token, []).render(scope, {})
|
||||
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 resolve identifier hash', async function () {
|
||||
await tag.construct(token, []).render(scope, {})
|
||||
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 accept space between key/value', async function () {
|
||||
await tag.construct(token, []).render(scope, {})
|
||||
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 number value hash', async function () {
|
||||
await tag.construct(token, []).render(scope, {})
|
||||
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'
|
||||
}))
|
||||
it('should resolve property access hash', async function () {
|
||||
await tag.construct(token, []).render(scope, {})
|
||||
expect(spy).to.have.been.calledWithMatch(scope, {
|
||||
dd: 'uoo'
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+20
-19
@@ -1,29 +1,30 @@
|
||||
'use strict'
|
||||
const Liquid = require('../../src')
|
||||
const chai = require('chai')
|
||||
import Liquid from '../../src'
|
||||
import chai from 'chai'
|
||||
import sinonChai from 'chai-as-promised'
|
||||
|
||||
chai.use(sinonChai)
|
||||
const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/assign', function () {
|
||||
let liquid = Liquid()
|
||||
const liquid = Liquid()
|
||||
it('should throw when variable expression illegal', function () {
|
||||
let src = '{% assign / %}'
|
||||
let ctx = {}
|
||||
const src = '{% assign / %}'
|
||||
const ctx = {}
|
||||
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/)
|
||||
})
|
||||
it('should support assign to a string', function () {
|
||||
let src = '{% assign foo="bar" %}{{foo}}'
|
||||
const src = '{% assign foo="bar" %}{{foo}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('bar')
|
||||
})
|
||||
it('should support assign to a number', function () {
|
||||
let src = '{% assign foo=10086 %}{{foo}}'
|
||||
const src = '{% assign foo=10086 %}{{foo}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('10086')
|
||||
})
|
||||
it('should shading rather than overwriting', function () {
|
||||
let ctx = {foo: 'foo'}
|
||||
let src = '{% assign foo="FOO" %}{{foo}}'
|
||||
const ctx = {foo: 'foo'}
|
||||
const src = '{% assign foo="FOO" %}{{foo}}'
|
||||
return liquid.parseAndRender(src, ctx)
|
||||
.then(x => {
|
||||
expect(x).to.equal('FOO')
|
||||
@@ -31,37 +32,37 @@ describe('tags/assign', function () {
|
||||
})
|
||||
})
|
||||
it('should assign as array', function () {
|
||||
let src = '{% assign foo=(1..3) %}{{foo}}'
|
||||
const src = '{% assign foo=(1..3) %}{{foo}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('[1,2,3]')
|
||||
})
|
||||
it('should assign as filter result', function () {
|
||||
let src = '{% assign foo="a b" | capitalize | split: " " | first %}{{foo}}'
|
||||
const src = '{% assign foo="a b" | capitalize | split: " " | first %}{{foo}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('A')
|
||||
})
|
||||
it('should assign var-1', function () {
|
||||
let src = '{% assign var-1 = 5 %}{{ var-1 }}'
|
||||
const src = '{% assign var-1 = 5 %}{{ var-1 }}'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
|
||||
})
|
||||
it('should assign var-', function () {
|
||||
let src = '{% assign var- = 5 %}{{ var- }}'
|
||||
const src = '{% assign var- = 5 %}{{ var- }}'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
|
||||
})
|
||||
it('should assign -var', function () {
|
||||
let src = '{% assign -let = 5 %}{{ -let }}'
|
||||
const src = '{% assign -let = 5 %}{{ -let }}'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
|
||||
})
|
||||
it('should assign -5-5', function () {
|
||||
let src = '{% assign -5-5 = 5 %}{{ -5-5 }}'
|
||||
const src = '{% assign -5-5 = 5 %}{{ -5-5 }}'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
|
||||
})
|
||||
it('should assign 4-3', function () {
|
||||
let src = '{% assign 4-3 = 5 %}{{ 4-3 }}'
|
||||
const src = '{% assign 4-3 = 5 %}{{ 4-3 }}'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
|
||||
})
|
||||
it('should not assign -6', function () {
|
||||
let src = '{% assign -6 = 5 %}{{ -6 }}'
|
||||
const src = '{% assign -6 = 5 %}{{ -6 }}'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal('-6')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,17 +5,17 @@ const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/capture', function () {
|
||||
let liquid = Liquid()
|
||||
const liquid = Liquid()
|
||||
|
||||
it('should support capture', function () {
|
||||
let src = '{% capture f %}{{"a" | capitalize}}{%endcapture%}{{f}}'
|
||||
const src = '{% capture f %}{{"a" | capitalize}}{%endcapture%}{{f}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('A')
|
||||
})
|
||||
|
||||
it('should shading rather than overwriting', function () {
|
||||
let src = '{% capture var %}10{% endcapture %}{{var}}'
|
||||
let ctx = {'var': 20}
|
||||
const src = '{% capture var %}10{% endcapture %}{{var}}'
|
||||
const ctx = {'var': 20}
|
||||
return liquid.parseAndRender(src, ctx)
|
||||
.then(x => {
|
||||
expect(x).to.equal('10')
|
||||
@@ -24,13 +24,13 @@ describe('tags/capture', function () {
|
||||
})
|
||||
|
||||
it('should throw on invalid identifier', function () {
|
||||
let src = '{% capture = %}{%endcapture%}'
|
||||
const src = '{% capture = %}{%endcapture%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/= not valid identifier/)
|
||||
})
|
||||
|
||||
it('should throw when capture not closed', function () {
|
||||
let src = '{%capture c%}{{c}}'
|
||||
const src = '{%capture c%}{{c}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/tag .* not closed/)
|
||||
})
|
||||
|
||||
+8
-8
@@ -5,46 +5,46 @@ const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/case', function () {
|
||||
let liquid = Liquid()
|
||||
const liquid = Liquid()
|
||||
|
||||
it('should reject if not closed', function () {
|
||||
let src = '{% case "foo"%}'
|
||||
const src = '{% case "foo"%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/{% case "foo"%} not closed/)
|
||||
})
|
||||
it('should hit the specified case', function () {
|
||||
let src = '{% case "foo"%}' +
|
||||
const src = '{% case "foo"%}' +
|
||||
'{% when "foo" %}foo{% when "bar"%}bar' +
|
||||
'{%endcase%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('foo')
|
||||
})
|
||||
it('should resolve empty string if not hit', function () {
|
||||
let src = '{% case empty %}' +
|
||||
const src = '{% case empty %}' +
|
||||
'{% when "foo" %}foo{% when ""%}bar' +
|
||||
'{%endcase%}'
|
||||
let ctx = {
|
||||
const ctx = {
|
||||
empty: ''
|
||||
}
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('bar')
|
||||
})
|
||||
it('should accept empty string as branch name', function () {
|
||||
let src = '{% case false %}' +
|
||||
const src = '{% case false %}' +
|
||||
'{% when "foo" %}foo{% when ""%}bar' +
|
||||
'{%endcase%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
it('should support boolean case', function () {
|
||||
let src = '{% case false %}' +
|
||||
const src = '{% case false %}' +
|
||||
'{% when "foo" %}foo{% when false%}bar' +
|
||||
'{%endcase%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('bar')
|
||||
})
|
||||
it('should support else branch', function () {
|
||||
let src = '{% case "a" %}' +
|
||||
const src = '{% case "a" %}' +
|
||||
'{% when "b" %}b{% when "c"%}c{%else %}d' +
|
||||
'{%endcase%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
|
||||
@@ -5,29 +5,29 @@ const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/comment', function () {
|
||||
let liquid = Liquid()
|
||||
const liquid = Liquid()
|
||||
it('should support empty content', function () {
|
||||
let src = '{% comment %}{% raw%}'
|
||||
const src = '{% comment %}{% raw%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/{% comment %} not closed/)
|
||||
})
|
||||
it('should ignore plain string', function () {
|
||||
let src = 'My name is {% comment %}super{% endcomment %} Shopify.'
|
||||
const src = 'My name is {% comment %}super{% endcomment %} Shopify.'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('My name is Shopify.')
|
||||
})
|
||||
it('should ignore output tokens', function () {
|
||||
let src = '{% comment %}\n{{ foo}} \n{% endcomment %}'
|
||||
const src = '{% comment %}\n{{ foo}} \n{% endcomment %}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
it('should ignore tag tokens', function () {
|
||||
let src = '{% comment %}{%if true%}true{%else%}false{%endif%}{% endcomment %}'
|
||||
const src = '{% comment %}{%if true%}true{%else%}false{%endif%}{% endcomment %}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
it('should ignore un-balenced tag tokens', function () {
|
||||
let src = '{% comment %}{%if true%}true{%else%}false{% endcomment %}'
|
||||
const src = '{% comment %}{%if true%}true{%else%}false{% endcomment %}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
|
||||
+6
-6
@@ -5,10 +5,10 @@ const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/cycle', function () {
|
||||
let liquid = Liquid()
|
||||
const liquid = Liquid()
|
||||
|
||||
it('should support cycle', function () {
|
||||
let src = "{% cycle '1', '2', '3' %}"
|
||||
const src = "{% cycle '1', '2', '3' %}"
|
||||
return expect(liquid.parseAndRender(src + src + src + src))
|
||||
.to.eventually.equal('1231')
|
||||
})
|
||||
@@ -19,8 +19,8 @@ describe('tags/cycle', function () {
|
||||
})
|
||||
|
||||
it('should support cycle in for block', function () {
|
||||
let src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}'
|
||||
let ctx = {
|
||||
const src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}'
|
||||
const ctx = {
|
||||
one: 1
|
||||
}
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
@@ -28,10 +28,10 @@ describe('tags/cycle', function () {
|
||||
})
|
||||
|
||||
it('should support cycle group', function () {
|
||||
let src = "{% cycle one: '1', '2', '3'%}" +
|
||||
const src = "{% cycle one: '1', '2', '3'%}" +
|
||||
"{% cycle 1: '1', '2', '3'%}" +
|
||||
"{% cycle 2: '1', '2', '3'%}"
|
||||
let ctx = {
|
||||
const ctx = {
|
||||
one: 1
|
||||
}
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
|
||||
+11
-11
@@ -5,22 +5,22 @@ const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/decrement', function () {
|
||||
let liquid = Liquid()
|
||||
const liquid = Liquid()
|
||||
it('should throw when variable expression illegal', function () {
|
||||
let src = '{% decrement / %}{{var}}'
|
||||
let ctx = {}
|
||||
const src = '{% decrement / %}{{var}}'
|
||||
const ctx = {}
|
||||
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/)
|
||||
})
|
||||
|
||||
it('should decrement undefined variable', function () {
|
||||
let src = '{% decrement var %}{% decrement var %}{% decrement var %}'
|
||||
const src = '{% decrement var %}{% decrement var %}{% decrement var %}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('-1-2-3')
|
||||
})
|
||||
|
||||
it('should decrement defined variable', function () {
|
||||
let src = '{% decrement var %}{% decrement var %}{% decrement var %}'
|
||||
let ctx = {'var': 10}
|
||||
const src = '{% decrement var %}{% decrement var %}{% decrement var %}'
|
||||
const ctx = {'var': 10}
|
||||
return liquid.parseAndRender(src, ctx)
|
||||
.then(x => {
|
||||
expect(x).to.equal('987')
|
||||
@@ -29,31 +29,31 @@ describe('tags/decrement', function () {
|
||||
})
|
||||
|
||||
it('should be independent from assign', function () {
|
||||
let src = '{% assign var=10 %}{% decrement var %}{% decrement var %}{% decrement var %}'
|
||||
const src = '{% assign var=10 %}{% decrement var %}{% decrement var %}{% decrement var %}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('-1-2-3')
|
||||
})
|
||||
|
||||
it('should be independent from capture', function () {
|
||||
let src = '{% capture var %}10{% endcapture %}{% decrement var %}{% decrement var %}{% decrement var %}'
|
||||
const src = '{% capture var %}10{% endcapture %}{% decrement var %}{% decrement var %}{% decrement var %}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('-1-2-3')
|
||||
})
|
||||
|
||||
it('should not shading assign', function () {
|
||||
let src = '{% assign var=10 %}{% decrement var %}{% decrement var %}{% decrement var %} {{var}}'
|
||||
const src = '{% assign var=10 %}{% decrement var %}{% decrement var %}{% decrement var %} {{var}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('-1-2-3 10')
|
||||
})
|
||||
|
||||
it('should not shading capture', function () {
|
||||
let src = '{% capture var %}10{% endcapture %}{% decrement var %}{% decrement var %}{% decrement var %} {{var}}'
|
||||
const src = '{% capture var %}10{% endcapture %}{% decrement var %}{% decrement var %}{% decrement var %} {{var}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('-1-2-3 10')
|
||||
})
|
||||
|
||||
it('should share the same variable with increment', function () {
|
||||
let src = '{%increment var%}{%increment var%}{%decrement var%}{%decrement var%}{%increment var%}'
|
||||
const src = '{%increment var%}{%increment var%}{%decrement var%}{%decrement var%}{%increment var%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('01100')
|
||||
})
|
||||
|
||||
+28
-28
@@ -23,25 +23,25 @@ describe('tags/for', function () {
|
||||
}
|
||||
})
|
||||
it('should support array', function () {
|
||||
let src = '{%for c in alpha%}{{c}}{%endfor%}'
|
||||
const src = '{%for c in alpha%}{{c}}{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('abc')
|
||||
})
|
||||
|
||||
it('should support object', function () {
|
||||
let src = '{%for item in obj%}{{item[0]}},{{item[1]}}-{%else%}b{%endfor%}'
|
||||
const src = '{%for item in obj%}{{item[0]}},{{item[1]}}-{%else%}b{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('foo,bar-coo,haa-')
|
||||
})
|
||||
|
||||
describe('scope', function () {
|
||||
it('should read super scope', function () {
|
||||
let src = '{%for a in (1..2)%}{{num}}{%endfor%}'
|
||||
const src = '{%for a in (1..2)%}{{num}}{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, {num: 1}))
|
||||
.to.eventually.equal('11')
|
||||
})
|
||||
it('should write super scope', function () {
|
||||
let src = '{%for a in (1..2)%}{{num}}{%assign num = 2%}{%endfor%}'
|
||||
const src = '{%for a in (1..2)%}{{num}}{%assign num = 2%}{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, {num: 1}))
|
||||
.to.eventually.equal('12')
|
||||
})
|
||||
@@ -49,13 +49,13 @@ describe('tags/for', function () {
|
||||
|
||||
describe('illegal', function () {
|
||||
it('should reject when for not closed', function () {
|
||||
let src = '{%for c in alpha%}{{c}}'
|
||||
const src = '{%for c in alpha%}{{c}}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.be.rejectedWith(/tag .* not closed/)
|
||||
})
|
||||
|
||||
it('should reject when inner templates rejected', function () {
|
||||
let src = '{%for c in alpha%}{%throwingTag%}{%endfor%}'
|
||||
const src = '{%for c in alpha%}{%throwingTag%}{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.be.rejectedWith(/intended render error/)
|
||||
})
|
||||
@@ -63,51 +63,51 @@ describe('tags/for', function () {
|
||||
|
||||
describe('else', function () {
|
||||
it('should goto else for empty array', function () {
|
||||
let src = '{%for c in emptyArray%}a{%else%}b{%endfor%}'
|
||||
const src = '{%for c in emptyArray%}a{%else%}b{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('b')
|
||||
})
|
||||
|
||||
it('should treat non-empty string as one single element', function () {
|
||||
let src = '{%for c in "abc"%}x{{c}}{%else%}y{%endfor%}'
|
||||
const src = '{%for c in "abc"%}x{{c}}{%else%}y{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('xabc')
|
||||
})
|
||||
|
||||
it('should goto else for empty string', function () {
|
||||
let src = '{%for c in ""%}a{%else%}b{%endfor%}'
|
||||
const src = '{%for c in ""%}a{%else%}b{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('b')
|
||||
})
|
||||
|
||||
it('should goto else for empty string object', function () {
|
||||
// it should be false although `new String` is none-conform
|
||||
let src = '{%for c in strObj%}a{%else%}b{%endfor%}'
|
||||
const src = '{%for c in strObj%}a{%else%}b{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('b')
|
||||
})
|
||||
|
||||
it('should goto else for empty object', function () {
|
||||
let src = '{%for c in emptyObj%}a{%else%}b{%endfor%}'
|
||||
const src = '{%for c in emptyObj%}a{%else%}b{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('b')
|
||||
})
|
||||
|
||||
it('should goto else for null-prototyped object', function () {
|
||||
let src = '{%for c in nullProtoObj%}a{%else%}b{%endfor%}'
|
||||
const src = '{%for c in nullProtoObj%}a{%else%}b{%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('b')
|
||||
})
|
||||
})
|
||||
|
||||
it('should support for with forloop', function () {
|
||||
let src = '{%for c in alpha%}' +
|
||||
const src = '{%for c in alpha%}' +
|
||||
'{{forloop.first}}.{{forloop.index}}.{{forloop.index0}}.' +
|
||||
'{{forloop.last}}.{{forloop.length}}.' +
|
||||
'{{forloop.rindex}}.{{forloop.rindex0}}' +
|
||||
'{{c}}\n' +
|
||||
'{%endfor%}'
|
||||
let dst = 'true.1.0.false.3.3.2a\n' +
|
||||
const dst = 'true.1.0.false.3.3.2a\n' +
|
||||
'false.2.1.false.3.2.1b\n' +
|
||||
'false.3.2.true.3.1.0c\n'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
@@ -115,14 +115,14 @@ describe('tags/for', function () {
|
||||
})
|
||||
|
||||
it('should support for with continue', function () {
|
||||
let src = '{% for i in (1..5) %}' +
|
||||
const src = '{% for i in (1..5) %}' +
|
||||
'{{i}}{% continue %}after' +
|
||||
'{% endfor %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('12345')
|
||||
})
|
||||
it('should support for with break', function () {
|
||||
let src = '{% for i in (one..5) %}' +
|
||||
const src = '{% for i in (one..5) %}' +
|
||||
'{% if i == 4 %}{% break %}{% endif %}' +
|
||||
'{{ i }}' +
|
||||
'{% endfor %}'
|
||||
@@ -132,22 +132,22 @@ describe('tags/for', function () {
|
||||
|
||||
describe('limit', function () {
|
||||
it('should support for with limit', function () {
|
||||
let src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}'
|
||||
const src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('12')
|
||||
})
|
||||
it('should set forloop.last properly', function () {
|
||||
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.last}} {%endfor%}'
|
||||
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.last}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('false true ')
|
||||
})
|
||||
it('should set forloop.first properly', function () {
|
||||
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.first}} {%endfor%}'
|
||||
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.first}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('true false ')
|
||||
})
|
||||
it('should set forloop.length properly', function () {
|
||||
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.length}} {%endfor%}'
|
||||
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.length}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('2 2 ')
|
||||
})
|
||||
@@ -155,27 +155,27 @@ describe('tags/for', function () {
|
||||
|
||||
describe('offset', function () {
|
||||
it('should support offset with limit', function () {
|
||||
let src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}'
|
||||
const src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('67')
|
||||
})
|
||||
it('should set index properly', function () {
|
||||
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index}} {%endfor%}'
|
||||
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('1 2 ')
|
||||
})
|
||||
it('should set index0 properly', function () {
|
||||
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index0}} {%endfor%}'
|
||||
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index0}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('0 1 ')
|
||||
})
|
||||
it('should set rindex properly', function () {
|
||||
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex}} {%endfor%}'
|
||||
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('2 1 ')
|
||||
})
|
||||
it('should set rindex0 properly', function () {
|
||||
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex0}} {%endfor%}'
|
||||
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex0}} {%endfor%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('1 0 ')
|
||||
})
|
||||
@@ -183,19 +183,19 @@ describe('tags/for', function () {
|
||||
|
||||
describe('reverse', function () {
|
||||
it('should support for reversed in the last position', function () {
|
||||
let src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}'
|
||||
const src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('21')
|
||||
})
|
||||
|
||||
it('should support for reversed in the first position', function () {
|
||||
let src = '{% for i in (1..5) reversed limit:2 %}{{ i }}{% endfor %}'
|
||||
const src = '{% for i in (1..5) reversed limit:2 %}{{ i }}{% endfor %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('21')
|
||||
})
|
||||
|
||||
it('should support for reversed in the middle position', function () {
|
||||
let src = '{% for i in (1..5) offset:2 reversed limit:4 %}{{ i }}{% endfor %}'
|
||||
const src = '{% for i in (1..5) offset:2 reversed limit:4 %}{{ i }}{% endfor %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('543')
|
||||
})
|
||||
|
||||
+20
-20
@@ -5,8 +5,8 @@ const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/if', function () {
|
||||
let liquid = Liquid()
|
||||
let ctx = {
|
||||
const liquid = Liquid()
|
||||
const ctx = {
|
||||
one: 1,
|
||||
two: 2,
|
||||
emptyString: '',
|
||||
@@ -14,101 +14,101 @@ describe('tags/if', function () {
|
||||
}
|
||||
|
||||
it('should throw if not closed', function () {
|
||||
let src = '{% if false%}yes'
|
||||
const src = '{% if false%}yes'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.be.rejectedWith(/tag {% if false%} not closed/)
|
||||
})
|
||||
it('should support nested', function () {
|
||||
let src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}'
|
||||
const src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
|
||||
describe('single value as condition', function () {
|
||||
it('should support boolean', function () {
|
||||
let src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}'
|
||||
const src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('2')
|
||||
})
|
||||
it('should treat Array truthy', function () {
|
||||
let src = '{%if emptyArray%}a{%endif%}'
|
||||
const src = '{%if emptyArray%}a{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('a')
|
||||
})
|
||||
it('should return true if empty string', function () {
|
||||
let src = '{%if emptyString%}a{%endif%}'
|
||||
const src = '{%if emptyString%}a{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('a')
|
||||
})
|
||||
})
|
||||
describe('expression as condition', function () {
|
||||
it('should support ==', function () {
|
||||
let src = '{% if 2==3 %}yes{%else%}no{%endif%}'
|
||||
const src = '{% if 2==3 %}yes{%else%}no{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
it('should support >=', function () {
|
||||
let src = '{% if 1>=2 and one<two %}a{%endif%}'
|
||||
const src = '{% if 1>=2 and one<two %}a{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
it('should support !=', function () {
|
||||
let src = '{% if one!=two %}yes{%else%}no{%endif%}'
|
||||
const src = '{% if one!=two %}yes{%else%}no{%endif%}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('yes')
|
||||
})
|
||||
it('should support value and expression', function () {
|
||||
let src = `X{%if version and version != '' %}x{{version}}y{%endif%}Y`
|
||||
let ctx = { 'version': '' }
|
||||
const src = `X{%if version and version != '' %}x{{version}}y{%endif%}Y`
|
||||
const ctx = { 'version': '' }
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('XY')
|
||||
})
|
||||
})
|
||||
describe('comparasion to null', function () {
|
||||
it('should evaluate false for null < 10', function () {
|
||||
let src = '{% if null < 10 %}yes{% else %}no{% endif %}'
|
||||
const src = '{% if null < 10 %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for null > 10', function () {
|
||||
let src = '{% if null > 10 %}yes{% else %}no{% endif %}'
|
||||
const src = '{% if null > 10 %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for null <= 10', function () {
|
||||
let src = '{% if null <= 10 %}yes{% else %}no{% endif %}'
|
||||
const src = '{% if null <= 10 %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for null >= 10', function () {
|
||||
let src = '{% if null >= 10 %}yes{% else %}no{% endif %}'
|
||||
const src = '{% if null >= 10 %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for 10 < null', function () {
|
||||
let src = '{% if 10 < null %}yes{% else %}no{% endif %}'
|
||||
const src = '{% if 10 < null %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for 10 > null', function () {
|
||||
let src = '{% if 10 > null %}yes{% else %}no{% endif %}'
|
||||
const src = '{% if 10 > null %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for 10 <= null', function () {
|
||||
let src = '{% if 10 <= null %}yes{% else %}no{% endif %}'
|
||||
const src = '{% if 10 <= null %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
it('should evaluate false for 10 >= null', function () {
|
||||
let src = '{% if 10 >= null %}yes{% else %}no{% endif %}'
|
||||
const src = '{% if 10 >= null %}yes{% else %}no{% endif %}'
|
||||
return expect(liquid.parseAndRender(src, ctx))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
|
||||
@@ -95,7 +95,7 @@ describe('tags/include', function () {
|
||||
'/card.html': '<p>{{person.firstName}} {{person.lastName}}<br/>{% include "address" %}</p>',
|
||||
'/address.html': 'City: {{person.address.city}}'
|
||||
})
|
||||
let ctx = {
|
||||
const ctx = {
|
||||
person: {
|
||||
firstName: 'Joe',
|
||||
lastName: 'Shmoe',
|
||||
@@ -114,7 +114,7 @@ describe('tags/include', function () {
|
||||
'/parent.html': 'X{% include child.html color:"red" %}Y',
|
||||
'/child.html': 'child with {{color}}'
|
||||
})
|
||||
let staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
|
||||
const staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
|
||||
return expect(staticLiquid.renderFile('parent.html')).to
|
||||
.eventually.equal('Xchild with redY')
|
||||
})
|
||||
@@ -124,7 +124,7 @@ describe('tags/include', function () {
|
||||
'/parent.html': 'X{% include bar/./../foo/child.html %}Y',
|
||||
'/foo/child.html': 'child'
|
||||
})
|
||||
let staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
|
||||
const staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
|
||||
return expect(staticLiquid.renderFile('parent.html')).to
|
||||
.eventually.equal('XchildY')
|
||||
})
|
||||
@@ -134,7 +134,7 @@ describe('tags/include', function () {
|
||||
'/parent.html': 'X{% include foo/child.html %}Y',
|
||||
'/foo/child.html': 'child'
|
||||
})
|
||||
let staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
|
||||
const staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
|
||||
return expect(staticLiquid.renderFile('parent.html')).to
|
||||
.eventually.equal('XchildY')
|
||||
})
|
||||
@@ -144,7 +144,7 @@ describe('tags/include', function () {
|
||||
'/parent.html': 'X{% include child.html, color:"red" %}Y',
|
||||
'/child.html': 'child with {{color}}'
|
||||
})
|
||||
let staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
|
||||
const staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
|
||||
return expect(staticLiquid.renderFile('parent.html')).to
|
||||
.eventually.equal('Xchild with redY')
|
||||
})
|
||||
|
||||
@@ -5,17 +5,17 @@ const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/increment', function () {
|
||||
let liquid = Liquid()
|
||||
const liquid = Liquid()
|
||||
|
||||
it('should increment undefined variable', function () {
|
||||
let src = '{% increment one %}{% increment one %}{% increment one %}'
|
||||
const src = '{% increment one %}{% increment one %}{% increment one %}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('012')
|
||||
})
|
||||
|
||||
it('should increment defined variable', function () {
|
||||
let src = '{% increment one %}{% increment one %}{% increment one %}'
|
||||
let ctx = {one: 7}
|
||||
const src = '{% increment one %}{% increment one %}{% increment one %}'
|
||||
const ctx = {one: 7}
|
||||
return liquid.parseAndRender(src, ctx)
|
||||
.then(x => {
|
||||
expect(x).to.equal('789')
|
||||
@@ -24,25 +24,25 @@ describe('tags/increment', function () {
|
||||
})
|
||||
|
||||
it('should be independent from assign', function () {
|
||||
let src = '{% assign var=10 %}{% increment var %}{% increment var %}{% increment var %}'
|
||||
const src = '{% assign var=10 %}{% increment var %}{% increment var %}{% increment var %}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('012')
|
||||
})
|
||||
|
||||
it('should be independent from capture', function () {
|
||||
let src = '{% capture var %}10{% endcapture %}{% increment var %}{% increment var %}{% increment var %}'
|
||||
const src = '{% capture var %}10{% endcapture %}{% increment var %}{% increment var %}{% increment var %}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('012')
|
||||
})
|
||||
|
||||
it('should not shading assign', function () {
|
||||
let src = '{% assign var=10 %}{% increment var %}{% increment var %}{% increment var %} {{var}}'
|
||||
const src = '{% assign var=10 %}{% increment var %}{% increment var %}{% increment var %} {{var}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('012 10')
|
||||
})
|
||||
|
||||
it('should not shading capture', function () {
|
||||
let src = '{% capture var %}10{% endcapture %}{% increment var %}{% increment var %}{% increment var %} {{var}}'
|
||||
const src = '{% capture var %}10{% endcapture %}{% increment var %}{% increment var %}{% increment var %} {{var}}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('012 10')
|
||||
})
|
||||
|
||||
+8
-8
@@ -21,7 +21,7 @@ describe('tags/layout', function () {
|
||||
mock({
|
||||
'/parent.html': 'parent'
|
||||
})
|
||||
let src = '{% layout "parent" %}{%block%}A'
|
||||
const src = '{% layout "parent" %}{%block%}A'
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.be.rejectedWith(/tag {%block%} not closed/)
|
||||
})
|
||||
@@ -39,7 +39,7 @@ describe('tags/layout', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{%block%}{%endblock%}Y'
|
||||
})
|
||||
let src = '{% layout "parent.html" %}{%block%}A{%endblock%}'
|
||||
const src = '{% layout "parent.html" %}{%block%}A{%endblock%}'
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.eventually.equal('XAY')
|
||||
})
|
||||
@@ -47,7 +47,7 @@ describe('tags/layout', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{%block%}{%endblock%}Y'
|
||||
})
|
||||
let src = '{% layout "parent.html" %}A'
|
||||
const src = '{% layout "parent.html" %}A'
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.eventually.equal('XAY')
|
||||
})
|
||||
@@ -56,7 +56,7 @@ describe('tags/layout', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{% block "a"%}{% endblock %}Y{% block b%}{%endblock%}Z'
|
||||
})
|
||||
let src = '{% layout "parent.html" %}' +
|
||||
const src = '{% layout "parent.html" %}' +
|
||||
'{%block a%}A{%endblock%}' +
|
||||
'{%block b%}B{%endblock%}'
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
@@ -66,7 +66,7 @@ describe('tags/layout', function () {
|
||||
mock({
|
||||
'/parent.html': 'X{% block "a"%}A{% endblock %}Y{% block b%}B{%endblock%}Z'
|
||||
})
|
||||
let src = '{% layout "parent.html" %}{%block a%}a{%endblock%}'
|
||||
const src = '{% layout "parent.html" %}{%block a%}a{%endblock%}'
|
||||
return expect(liquid.parseAndRender(src)).to
|
||||
.eventually.equal('XaYBZ')
|
||||
})
|
||||
@@ -113,7 +113,7 @@ describe('tags/layout', function () {
|
||||
'/parent.html': '{{color}}{%block%}{%endblock%}',
|
||||
'/main.html': '{% layout parent.html color:"black"%}{%block%}A{%endblock%}'
|
||||
})
|
||||
let staticLiquid = Liquid({ root: '/', dynamicPartials: false })
|
||||
const staticLiquid = Liquid({ root: '/', dynamicPartials: false })
|
||||
return expect(staticLiquid.renderFile('/main.html')).to
|
||||
.eventually.equal('blackA')
|
||||
})
|
||||
@@ -123,7 +123,7 @@ describe('tags/layout', function () {
|
||||
'/foo/parent.html': '{{color}}{%block%}{%endblock%}',
|
||||
'/main.html': '{% layout bar/../foo/parent.html color:"black"%}{%block%}A{%endblock%}'
|
||||
})
|
||||
let staticLiquid = Liquid({ root: '/', dynamicPartials: false })
|
||||
const staticLiquid = Liquid({ root: '/', dynamicPartials: false })
|
||||
return expect(staticLiquid.renderFile('/main.html')).to
|
||||
.eventually.equal('blackA')
|
||||
})
|
||||
@@ -133,7 +133,7 @@ describe('tags/layout', function () {
|
||||
'/foo/parent.html': '{{color}}{%block%}{%endblock%}',
|
||||
'/main.html': '{% layout foo/parent.html color:"black"%}{%block%}A{%endblock%}'
|
||||
})
|
||||
let staticLiquid = Liquid({ root: '/', dynamicPartials: false })
|
||||
const staticLiquid = Liquid({ root: '/', dynamicPartials: false })
|
||||
return expect(staticLiquid.renderFile('/main.html')).to
|
||||
.eventually.equal('blackA')
|
||||
})
|
||||
|
||||
+11
-13
@@ -5,21 +5,19 @@ const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/raw', function () {
|
||||
let liquid = Liquid()
|
||||
it('should support raw 1', function () {
|
||||
return expect(liquid.parseAndRender('{% raw%}'))
|
||||
.to.be.rejectedWith(/{% raw%} not closed/)
|
||||
const liquid = Liquid()
|
||||
it('should support raw 1', async function () {
|
||||
const p = liquid.parseAndRender('{% raw%}')
|
||||
return expect(p).be.rejectedWith(/{% raw%} not closed/)
|
||||
})
|
||||
it('should support raw 2', function () {
|
||||
let src = '{% raw %}{{ 5 | plus: 6 }}{% endraw %} is equal to 11.'
|
||||
let dst = '{{ 5 | plus: 6 }} is equal to 11.'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal(dst)
|
||||
it('should support raw 2', async function () {
|
||||
const src = '{% raw %}{{ 5 | plus: 6 }}{% endraw %} is equal to 11.'
|
||||
const dst = '{{ 5 | plus: 6 }} is equal to 11.'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
it('should support raw 3', function () {
|
||||
let src = '{% raw %}\n{{ foo}} \n{% endraw %}'
|
||||
let dst = '\n{{ foo}} \n'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal(dst)
|
||||
const src = '{% raw %}\n{{ foo}} \n{% endraw %}'
|
||||
const dst = '\n{{ foo}} \n'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
})
|
||||
|
||||
+19
-19
@@ -5,52 +5,52 @@ const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/tablerow', function () {
|
||||
let liquid = Liquid()
|
||||
const liquid = Liquid()
|
||||
|
||||
it('should support tablerow', function () {
|
||||
let src = '{% tablerow i in (1..3)%}{{ i }}{% endtablerow %}'
|
||||
let dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>'
|
||||
const src = '{% tablerow i in (1..3)%}{{ i }}{% endtablerow %}'
|
||||
const dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('should support cols', function () {
|
||||
let src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}'
|
||||
let ctx = {
|
||||
const src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}'
|
||||
const ctx = {
|
||||
alpha: ['a', 'b', 'c']
|
||||
}
|
||||
let dst =
|
||||
const dst =
|
||||
'<tr class="row1"><td class="col1">a</td><td class="col2">b</td></tr>' +
|
||||
'<tr class="row2"><td class="col1">c</td></tr>'
|
||||
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('should support cols set to 0', function () {
|
||||
let src = '{% tablerow i in (1..3) cols:0 %}{{ i }}{% endtablerow %}'
|
||||
let dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>'
|
||||
const src = '{% tablerow i in (1..3) cols:0 %}{{ i }}{% endtablerow %}'
|
||||
const dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('should support empty tablerow', function () {
|
||||
let src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}'
|
||||
let dst = ''
|
||||
const src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}'
|
||||
const dst = ''
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('should support empty array', function () {
|
||||
let src = '{% tablerow i in alpha.z cols:2 %}{{ i }}{% endtablerow %}'
|
||||
let dst = ''
|
||||
const src = '{% tablerow i in alpha.z cols:2 %}{{ i }}{% endtablerow %}'
|
||||
const dst = ''
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('should throw when tablerow not closed', function () {
|
||||
let src = '{% tablerow i in (1..0) cols:2 %}{{ i }}'
|
||||
const 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 () {
|
||||
let src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}'
|
||||
let dst =
|
||||
const src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}'
|
||||
const dst =
|
||||
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
|
||||
'<tr class="row2"><td class="col1">3</td><td class="col2">4</td></tr>' +
|
||||
'<tr class="row3"><td class="col1">5</td></tr>'
|
||||
@@ -58,16 +58,16 @@ describe('tags/tablerow', function () {
|
||||
})
|
||||
|
||||
it('should support tablerow with limit', function () {
|
||||
let src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}'
|
||||
let dst =
|
||||
const src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}'
|
||||
const dst =
|
||||
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
|
||||
'<tr class="row2"><td class="col1">3</td></tr>'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
|
||||
it('should support tablerow with offset', function () {
|
||||
let src = '{% tablerow i in (1..5) cols:2 offset:3 %}{{ i }}{% endtablerow %}'
|
||||
let dst = '<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>'
|
||||
const src = '{% tablerow i in (1..5) cols:2 offset:3 %}{{ i }}{% endtablerow %}'
|
||||
const dst = '<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>'
|
||||
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
|
||||
})
|
||||
})
|
||||
|
||||
+6
-6
@@ -5,31 +5,31 @@ const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('tags/unless', function () {
|
||||
let liquid = Liquid()
|
||||
const liquid = Liquid()
|
||||
|
||||
it('should render else when predicate yields true', function () {
|
||||
// 0 is truthy
|
||||
let src = '{% unless 0 %}yes{%else%}no{%endunless%}'
|
||||
const src = '{% unless 0 %}yes{%else%}no{%endunless%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('no')
|
||||
})
|
||||
it('should render unless when predicate yields false', function () {
|
||||
let src = '{% unless false %}yes{%else%}no{%endunless%}'
|
||||
const src = '{% unless false %}yes{%else%}no{%endunless%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('yes')
|
||||
})
|
||||
it('should reject when tag not closed', function () {
|
||||
let src = '{% unless 1>2 %}yes'
|
||||
const src = '{% unless 1>2 %}yes'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.be.rejectedWith(/tag {% unless 1>2 %} not closed/)
|
||||
})
|
||||
it('should render unless when predicate yields false and else undefined', function () {
|
||||
let src = '{% unless 1>2 %}yes{%endunless%}'
|
||||
const src = '{% unless 1>2 %}yes{%endunless%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('yes')
|
||||
})
|
||||
it('should render "" when predicate yields false and else undefined', function () {
|
||||
let src = '{% unless 1<2 %}yes{%endunless%}'
|
||||
const src = '{% unless 1<2 %}yes{%endunless%}'
|
||||
return expect(liquid.parseAndRender(src))
|
||||
.to.eventually.equal('')
|
||||
})
|
||||
|
||||
+14
-14
@@ -5,8 +5,8 @@ const expect = chai.expect
|
||||
describe('tokenizer', function () {
|
||||
describe('parse', function () {
|
||||
it('should handle plain HTML', function () {
|
||||
let html = '<html><body><p>Lorem Ipsum</p></body></html>'
|
||||
let tokens = parse(html)
|
||||
const html = '<html><body><p>Lorem Ipsum</p></body></html>'
|
||||
const tokens = parse(html)
|
||||
|
||||
expect(tokens.length).to.equal(1)
|
||||
expect(tokens[0].value).to.equal(html)
|
||||
@@ -18,24 +18,24 @@ describe('tokenizer', function () {
|
||||
}).to.throw('illegal input')
|
||||
})
|
||||
it('should handle tag syntax', function () {
|
||||
let html = '<p>{% for p in a[1]%}</p>'
|
||||
let tokens = parse(html)
|
||||
const html = '<p>{% for p in a[1]%}</p>'
|
||||
const 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 value syntax', function () {
|
||||
let html = '<p>{{foo | date: "%Y-%m-%d"}}</p>'
|
||||
let tokens = parse(html)
|
||||
const html = '<p>{{foo | date: "%Y-%m-%d"}}</p>'
|
||||
const tokens = parse(html)
|
||||
|
||||
expect(tokens.length).to.equal(3)
|
||||
expect(tokens[1].type).to.equal('value')
|
||||
expect(tokens[1].value).to.equal('foo | date: "%Y-%m-%d"')
|
||||
})
|
||||
it('should handle consecutive value and tags', function () {
|
||||
let html = '{{foo}}{{bar}}{%foo%}{%bar%}'
|
||||
let tokens = parse(html)
|
||||
const html = '{{foo}}{{bar}}{%foo%}{%bar%}'
|
||||
const tokens = parse(html)
|
||||
|
||||
expect(tokens.length).to.equal(4)
|
||||
expect(tokens[0].type).to.equal('value')
|
||||
@@ -45,8 +45,8 @@ describe('tokenizer', function () {
|
||||
expect(tokens[2].value).to.equal('foo')
|
||||
})
|
||||
it('should keep white spaces and newlines', function () {
|
||||
let html = '{%foo%}\n{%bar %} \n {%alice%}'
|
||||
let tokens = parse(html)
|
||||
const html = '{%foo%}\n{%bar %} \n {%alice%}'
|
||||
const tokens = parse(html)
|
||||
expect(tokens.length).to.equal(5)
|
||||
expect(tokens[1].type).to.equal('html')
|
||||
expect(tokens[1].raw).to.equal('\n')
|
||||
@@ -54,16 +54,16 @@ describe('tokenizer', function () {
|
||||
expect(tokens[3].raw).to.equal(' \n ')
|
||||
})
|
||||
it('should handle multiple lines tag', function () {
|
||||
let html = '{%foo\na:a\nb:1.23\n%}'
|
||||
let tokens = parse(html)
|
||||
const html = '{%foo\na:a\nb:1.23\n%}'
|
||||
const tokens = parse(html)
|
||||
expect(tokens.length).to.equal(1)
|
||||
expect(tokens[0].type).to.equal('tag')
|
||||
expect(tokens[0].args).to.equal('a:a\nb:1.23')
|
||||
expect(tokens[0].raw).to.equal('{%foo\na:a\nb:1.23\n%}')
|
||||
})
|
||||
it('should handle multiple lines value', function () {
|
||||
let html = '{{foo\n|date:\n"%Y-%m-%d"\n}}'
|
||||
let tokens = parse(html)
|
||||
const html = '{{foo\n|date:\n"%Y-%m-%d"\n}}'
|
||||
const tokens = parse(html)
|
||||
expect(tokens.length).to.equal(1)
|
||||
expect(tokens[0].type).to.equal('value')
|
||||
expect(tokens[0].raw).to.equal('{{foo\n|date:\n"%Y-%m-%d"\n}}')
|
||||
|
||||
+6
-5
@@ -1,18 +1,19 @@
|
||||
const chai = require('chai')
|
||||
import chai from 'chai'
|
||||
import assert from '../../src/util/assert.js'
|
||||
|
||||
const expect = chai.expect
|
||||
const assert = require('../../src/util/assert.js')
|
||||
|
||||
describe('assert', function () {
|
||||
it('should not throw if predicate is truthy', function () {
|
||||
let fn = () => assert('foo', 'bar')
|
||||
const fn = () => assert('foo', 'bar')
|
||||
expect(fn).to.not.throw()
|
||||
})
|
||||
it('should not throw if predicate is truthy', function () {
|
||||
let fn = () => assert('', 'bar')
|
||||
const fn = () => assert('', 'bar')
|
||||
expect(fn).to.throw(/bar/)
|
||||
})
|
||||
it('should populate default message', function () {
|
||||
let fn = () => assert(false)
|
||||
const fn = () => assert(false)
|
||||
expect(fn).to.throw(/expect false to be true/)
|
||||
})
|
||||
})
|
||||
|
||||
+150
-236
@@ -7,7 +7,7 @@ const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
let engine = Liquid()
|
||||
let strictEngine = Liquid({
|
||||
const strictEngine = Liquid({
|
||||
strict_variables: true,
|
||||
strict_filters: true
|
||||
})
|
||||
@@ -18,80 +18,59 @@ describe('error', function () {
|
||||
})
|
||||
|
||||
describe('TokenizationError', function () {
|
||||
it('should throw TokenizationError when tag illegal', function () {
|
||||
return expect(engine.parseAndRender('{% . a %}', {})).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('TokenizationError')
|
||||
expect(err.message).to.contain('illegal tag syntax')
|
||||
})
|
||||
it('should throw TokenizationError when tag illegal', async function () {
|
||||
const err = await expect(engine.parseAndRender('{% . a %}', {})).be.rejected
|
||||
expect(err.name).to.equal('TokenizationError')
|
||||
expect(err.message).to.contain('illegal tag syntax')
|
||||
})
|
||||
it('should contain template content in err.message', function () {
|
||||
let html = ['1st', '2nd', 'X{% . a %} Y', '4th']
|
||||
let message = [
|
||||
it('should contain template content in err.message', async function () {
|
||||
const html = ['1st', '2nd', 'X{% . a %} Y', '4th']
|
||||
const message = [
|
||||
' 1| 1st',
|
||||
' 2| 2nd',
|
||||
'>> 3| X{% . a %} Y',
|
||||
' 4| 4th',
|
||||
'TokenizationError'
|
||||
]
|
||||
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.equal('illegal tag syntax, line:3')
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('TokenizationError')
|
||||
})
|
||||
const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
|
||||
expect(err.message).to.equal('illegal tag syntax, line:3')
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('TokenizationError')
|
||||
})
|
||||
it('should contain the whole template content in err.input', function () {
|
||||
let html = 'bar\nfoo{% . a %}\nfoo'
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.input).to.equal(html)
|
||||
})
|
||||
it('should contain the whole template content in err.input', async function () {
|
||||
const html = 'bar\nfoo{% . a %}\nfoo'
|
||||
const err = await expect(engine.parseAndRender(html)).be.rejected
|
||||
expect(err.input).to.equal(html)
|
||||
})
|
||||
it('should contain line number in err.line', function () {
|
||||
return expect(engine.parseAndRender('1\n2\n{% . a %}\n4', {})).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('TokenizationError')
|
||||
expect(err.line).to.equal(3)
|
||||
})
|
||||
it('should contain line number in err.line', async function () {
|
||||
const err = await expect(engine.parseAndRender('1\n2\n{% . a %}\n4')).be.rejected
|
||||
expect(err.name).to.equal('TokenizationError')
|
||||
expect(err.line).to.equal(3)
|
||||
})
|
||||
it('should contain stack in err.stack', function () {
|
||||
return expect(engine.parseAndRender('{% . a %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.contain('illegal tag syntax')
|
||||
expect(err.stack).to.contain('at Object.parse')
|
||||
})
|
||||
it('should contain stack in err.stack', async function () {
|
||||
const err = await expect(engine.parseAndRender('{% . a %}')).be.rejected
|
||||
expect(err.message).to.contain('illegal tag syntax')
|
||||
expect(err.stack).to.contain('at Object.parse')
|
||||
})
|
||||
describe('captureStackTrace compatibility', function () {
|
||||
let captureStackTrace = Error.captureStackTrace
|
||||
const captureStackTrace = Error.captureStackTrace
|
||||
before(() => (Error.captureStackTrace = null))
|
||||
after(() => (Error.captureStackTrace = captureStackTrace))
|
||||
it('should use empty string if captureStackTrace not defined', function () {
|
||||
return expect(engine.parseAndRender('{% . a %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.stack).to.contain('illegal tag syntax')
|
||||
expect(err.stack).to.not.contain('at Object.parse')
|
||||
})
|
||||
it('should be empty when captureStackTrace undefined', async function () {
|
||||
const err = await expect(engine.parseAndRender('{% . a %}')).be.rejected
|
||||
expect(err.stack).to.contain('illegal tag syntax')
|
||||
expect(err.stack).to.not.contain('at Object.parse')
|
||||
})
|
||||
})
|
||||
it('should contain file path in err.file', function () {
|
||||
let html = '<html>\n<head>\n\n{% . a %}\n\n'
|
||||
it('should contain file path in err.file', async function () {
|
||||
const html = '<html>\n<head>\n\n{% . a %}\n\n'
|
||||
mock({
|
||||
'/foo.html': html
|
||||
})
|
||||
return expect(engine.renderFile('/foo.html')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
mock.restore()
|
||||
expect(err.name).to.equal('TokenizationError')
|
||||
expect(err.file).to.equal(path.resolve('/foo.html'))
|
||||
})
|
||||
const err = await expect(engine.renderFile('/foo.html')).be.rejected
|
||||
mock.restore()
|
||||
expect(err.name).to.equal('TokenizationError')
|
||||
expect(err.file).to.equal(path.resolve('/foo.html'))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -106,55 +85,43 @@ describe('error', function () {
|
||||
}
|
||||
})
|
||||
engine.registerTag('rejectingTag', {
|
||||
render: function () {
|
||||
return Promise.reject(new Error('intended render reject'))
|
||||
render: async function () {
|
||||
throw new Error('intended render reject')
|
||||
}
|
||||
})
|
||||
engine.registerFilter('throwingFilter', () => {
|
||||
throw new Error('throwed by filter')
|
||||
})
|
||||
})
|
||||
it('should throw RenderError when tag throws', function () {
|
||||
let src = '{%throwingTag%}'
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('RenderError')
|
||||
expect(err.message).to.contain('intended render error')
|
||||
})
|
||||
it('should throw RenderError when tag throws', async function () {
|
||||
const src = '{%throwingTag%}'
|
||||
const err = await expect(engine.parseAndRender(src)).be.rejected
|
||||
expect(err.name).to.equal('RenderError')
|
||||
expect(err.message).to.contain('intended render error')
|
||||
})
|
||||
it('should throw RenderError when tag rejects', function () {
|
||||
let src = '{%rejectingTag%}'
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('RenderError')
|
||||
expect(err.message).to.contain('intended render reject')
|
||||
})
|
||||
it('should throw RenderError when tag rejects', async function () {
|
||||
const src = '{%rejectingTag%}'
|
||||
const err = await expect(engine.parseAndRender(src)).be.rejected
|
||||
expect(err.name).to.equal('RenderError')
|
||||
expect(err.message).to.contain('intended render reject')
|
||||
})
|
||||
it('should throw RenderError when filter throws', function () {
|
||||
let src = '{{1|throwingFilter}}'
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('RenderError')
|
||||
expect(err.message).to.contain('throwed by filter')
|
||||
})
|
||||
it('should throw RenderError when filter throws', async function () {
|
||||
const src = '{{1|throwingFilter}}'
|
||||
const err = await expect(engine.parseAndRender(src)).be.rejected
|
||||
expect(err.name).to.equal('RenderError')
|
||||
expect(err.message).to.contain('throwed by filter')
|
||||
})
|
||||
it('should not throw when variable undefined by default', function () {
|
||||
return expect(engine.parseAndRender('X{{a}}Y')).to.eventually.equal('XY')
|
||||
})
|
||||
it('should throw RenderError when variable not defined', function () {
|
||||
return expect(strictEngine.parseAndRender('{{a}}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (e) {
|
||||
expect(e).to.have.property('name', 'RenderError')
|
||||
expect(e.message).to.contain('undefined variable: a')
|
||||
})
|
||||
it('should throw RenderError when variable not defined', async function () {
|
||||
const err = await expect(strictEngine.parseAndRender('{{a}}')).be.rejected
|
||||
expect(err).to.have.property('name', 'RenderError')
|
||||
expect(err.message).to.contain('undefined variable: a')
|
||||
})
|
||||
it('should contain template context in err.stack', function () {
|
||||
let html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
|
||||
let message = [
|
||||
it('should contain template context in err.stack', async function () {
|
||||
const html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
|
||||
const message = [
|
||||
' 2| 2nd',
|
||||
' 3| 3rd',
|
||||
'>> 4| X{%throwingTag%} Y',
|
||||
@@ -163,15 +130,12 @@ describe('error', function () {
|
||||
' 7| 7th',
|
||||
'RenderError'
|
||||
]
|
||||
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.equal('intended render error, line:4')
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
|
||||
expect(err.message).to.equal('intended render error, line:4')
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
it('should contain original error info for {% layout %}', function () {
|
||||
it('should contain original error info for {% layout %}', async function () {
|
||||
mock({
|
||||
'/throwing-tag.html': [
|
||||
'1st',
|
||||
@@ -183,8 +147,8 @@ describe('error', function () {
|
||||
'7th'
|
||||
].join('\n')
|
||||
})
|
||||
let html = '{%layout "throwing-tag.html"%}'
|
||||
let message = [
|
||||
const html = '{%layout "throwing-tag.html"%}'
|
||||
const message = [
|
||||
' 2| 2nd',
|
||||
' 3| 3rd',
|
||||
'>> 4| X{%throwingTag%} Y',
|
||||
@@ -193,23 +157,20 @@ describe('error', function () {
|
||||
' 7| 7th',
|
||||
'RenderError'
|
||||
]
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
console.log(err.message)
|
||||
console.log(err.stack)
|
||||
expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4`)
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
const err = await expect(engine.parseAndRender(html)).be.rejected
|
||||
console.log(err.message)
|
||||
console.log(err.stack)
|
||||
expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4`)
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
it('should contain original error info for {% include %}', function () {
|
||||
let origin = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
|
||||
it('should contain original error info for {% include %}', async function () {
|
||||
const origin = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
|
||||
mock({
|
||||
'/throwing-tag.html': origin.join('\n')
|
||||
})
|
||||
let html = '{%include "throwing-tag.html"%}'
|
||||
let message = [
|
||||
const html = '{%include "throwing-tag.html"%}'
|
||||
const message = [
|
||||
' 2| 2nd',
|
||||
' 3| 3rd',
|
||||
'>> 4| X{%throwingTag%} Y',
|
||||
@@ -218,54 +179,39 @@ describe('error', function () {
|
||||
' 7| 7th',
|
||||
'RenderError'
|
||||
]
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4`)
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
const err = await expect(engine.parseAndRender(html)).be.rejected
|
||||
expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4`)
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
it('should contain the whole template content in err.input', function () {
|
||||
let html = 'bar\nfoo{%throwingTag%}\nfoo'
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.input).to.equal(html)
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
it('should contain the whole template content in err.input', async function () {
|
||||
const html = 'bar\nfoo{%throwingTag%}\nfoo'
|
||||
const err = await expect(engine.parseAndRender(html)).be.rejected
|
||||
expect(err.input).to.equal(html)
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
it('should contain line number in err.line', function () {
|
||||
let src = '1\n2\n{{1|throwingFilter}}\n4'
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.line).to.equal(3)
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
it('should contain line number in err.line', async function () {
|
||||
const src = '1\n2\n{{1|throwingFilter}}\n4'
|
||||
const err = await expect(engine.parseAndRender(src)).be.rejected
|
||||
expect(err.line).to.equal(3)
|
||||
expect(err.name).to.equal('RenderError')
|
||||
})
|
||||
it('should contain stack in err.stack', function () {
|
||||
return expect(engine.parseAndRender('{%rejectingTag%}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.contain('intended render reject')
|
||||
expect(err.stack).to.match(/at .*:\d+:\d+/)
|
||||
})
|
||||
it('should contain stack in err.stack', async function () {
|
||||
const err = await expect(engine.parseAndRender('{%rejectingTag%}')).be.rejected
|
||||
expect(err.message).to.contain('intended render reject')
|
||||
expect(err.stack).to.match(/at .*:\d+:\d+/)
|
||||
})
|
||||
|
||||
it('should contain file path in err.file', function () {
|
||||
let html = '<html>\n<head>\n\n{% throwingTag %}\n\n'
|
||||
it('should contain file path in err.file', async function () {
|
||||
const html = '<html>\n<head>\n\n{% throwingTag %}\n\n'
|
||||
mock({
|
||||
'/foo.html': html
|
||||
})
|
||||
return expect(engine.renderFile('/foo.html')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
mock.restore()
|
||||
console.log(err, err.name)
|
||||
expect(err.name).to.equal('RenderError')
|
||||
expect(err.file).to.equal(path.resolve('/foo.html'))
|
||||
})
|
||||
const err = await expect(engine.renderFile('/foo.html')).be.rejected
|
||||
mock.restore()
|
||||
console.log(err, err.name)
|
||||
expect(err.name).to.equal('RenderError')
|
||||
expect(err.file).to.equal(path.resolve('/foo.html'))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -278,53 +224,36 @@ describe('error', function () {
|
||||
}
|
||||
})
|
||||
})
|
||||
it('should throw RenderError when filter not defined', function () {
|
||||
return expect(strictEngine.parseAndRender('{{1 | a}}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (e) {
|
||||
expect(e).to.have.property('name', 'ParseError')
|
||||
expect(e.message).to.contain('undefined filter: a')
|
||||
})
|
||||
it('should throw RenderError when filter not defined', async function () {
|
||||
const err = await expect(strictEngine.parseAndRender('{{1 | a}}')).be.rejected
|
||||
expect(err).to.have.property('name', 'ParseError')
|
||||
expect(err.message).to.contain('undefined filter: a')
|
||||
})
|
||||
it('should throw ParseError when tag not closed', function () {
|
||||
return expect(engine.parseAndRender('{% if %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.message).to.contain('tag {% if %} not closed')
|
||||
})
|
||||
it('should throw ParseError when tag not closed', async function () {
|
||||
const err = await expect(engine.parseAndRender('{% if %}')).be.rejected
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.message).to.contain('tag {% if %} not closed')
|
||||
})
|
||||
it('should throw ParseError when tag parse throws', function () {
|
||||
let src = '{%throwsOnParse%}'
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.message).to.contain('intended parse error')
|
||||
})
|
||||
it('should throw ParseError when tag parse throws', async function () {
|
||||
const err = await expect(engine.parseAndRender('{%throwsOnParse%}')).be.rejected
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.message).to.contain('intended parse error')
|
||||
})
|
||||
it('should throw ParseError when tag not found', function () {
|
||||
let src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3'
|
||||
return expect(engine.parseAndRender(src)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.message).to.contain('tag -a not found')
|
||||
})
|
||||
it('should throw ParseError when tag not found', async function () {
|
||||
const src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3'
|
||||
const err = await expect(engine.parseAndRender(src)).be.rejected
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.message).to.contain('tag -a not found')
|
||||
})
|
||||
it('should throw ParseError when tag not exist', async function () {
|
||||
const err = await expect(engine.parseAndRender('{% a %}')).be.rejected
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.message).to.contain('tag a not found')
|
||||
})
|
||||
|
||||
it('should throw ParseError when tag not exist', function () {
|
||||
return expect(engine.parseAndRender('{% a %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.message).to.contain('tag a not found')
|
||||
})
|
||||
})
|
||||
|
||||
it('should contain template context in err.stack', function () {
|
||||
let html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th']
|
||||
let message = [
|
||||
it('should contain template context in err.stack', async function () {
|
||||
const html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th']
|
||||
const message = [
|
||||
' 2| 2nd',
|
||||
' 3| 3rd',
|
||||
'>> 4| X{% a %} {% enda %} Y',
|
||||
@@ -333,62 +262,47 @@ describe('error', function () {
|
||||
' 7| 7th',
|
||||
'ParseError: tag a not found'
|
||||
]
|
||||
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.equal('tag a not found, line:4')
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('ParseError')
|
||||
})
|
||||
const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
|
||||
expect(err.message).to.equal('tag a not found, line:4')
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
expect(err.name).to.equal('ParseError')
|
||||
})
|
||||
|
||||
it('should handle err.message when context not enough', function () {
|
||||
let html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th']
|
||||
let message = [
|
||||
it('should handle err.message when context not enough', async function () {
|
||||
const html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th']
|
||||
const message = [
|
||||
' 1| 1st',
|
||||
'>> 2| X{% a %} {% enda %} Y',
|
||||
' 3| 3rd',
|
||||
' 4| 4th',
|
||||
'ParseError: tag a not found'
|
||||
]
|
||||
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.message).to.equal('tag a not found, line:2')
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
})
|
||||
const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
|
||||
expect(err.message).to.equal('tag a not found, line:2')
|
||||
expect(err.stack).to.contain(message.join('\n'))
|
||||
})
|
||||
|
||||
it('should contain line number in err.line', function () {
|
||||
let html = '<html>\n<head>\n\n{% raw %}\n\n'
|
||||
return expect(engine.parseAndRender(html)).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.line).to.equal(4)
|
||||
})
|
||||
it('should contain line number in err.line', async function () {
|
||||
const html = '<html>\n<head>\n\n{% raw %}\n\n'
|
||||
const err = await expect(engine.parseAndRender(html)).be.rejected
|
||||
expect(err.line).to.equal(4)
|
||||
})
|
||||
|
||||
it('should contain stack in err.stack', function () {
|
||||
return expect(engine.parseAndRender('{% -a %}')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
expect(err.stack).to.contain('ParseError: tag -a not found')
|
||||
expect(err.stack).to.match(/at .*:\d+:\d+\)/)
|
||||
})
|
||||
it('should contain stack in err.stack', async function () {
|
||||
const err = await expect(engine.parseAndRender('{% -a %}')).be.rejected
|
||||
expect(err.stack).to.contain('ParseError: tag -a not found')
|
||||
expect(err.stack).to.match(/at .*:\d+:\d+\)/)
|
||||
})
|
||||
|
||||
it('should contain file path in err.file', function () {
|
||||
let html = '<html>\n<head>\n\n{% raw %}\n\n'
|
||||
it('should contain file path in err.file', async function () {
|
||||
const html = '<html>\n<head>\n\n{% raw %}\n\n'
|
||||
mock({
|
||||
'/foo.html': html
|
||||
})
|
||||
return expect(engine.renderFile('/foo.html')).to.eventually
|
||||
.be.rejected
|
||||
.then(function (err) {
|
||||
mock.restore()
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.file).to.equal(path.resolve('/foo.html'))
|
||||
})
|
||||
const err = await expect(engine.renderFile('/foo.html')).be.rejected
|
||||
mock.restore()
|
||||
expect(err.name).to.equal('ParseError')
|
||||
expect(err.file).to.equal(path.resolve('/foo.html'))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+11
-11
@@ -4,13 +4,13 @@ const expect = chai.expect
|
||||
chai.use(require('chai-as-promised'))
|
||||
chai.use(require('sinon-chai'))
|
||||
|
||||
let P = require('../../src/util/promise.js')
|
||||
const P = require('../../src/util/promise.js')
|
||||
|
||||
describe('util/promise', function () {
|
||||
describe('.anySeries()', function () {
|
||||
it('should resolve in series', function () {
|
||||
let spy1 = sinon.spy()
|
||||
let spy2 = sinon.spy()
|
||||
const spy1 = sinon.spy()
|
||||
const spy2 = sinon.spy()
|
||||
return P
|
||||
.anySeries(
|
||||
['first', 'second'],
|
||||
@@ -28,17 +28,17 @@ describe('util/promise', function () {
|
||||
.then(() => expect(spy2).to.have.been.calledAfter(spy1))
|
||||
})
|
||||
it('should reject when all rejected', function () {
|
||||
let p = P.anySeries(['first', 'second', 'third'],
|
||||
const p = P.anySeries(['first', 'second', 'third'],
|
||||
item => Promise.reject(new Error(item)))
|
||||
return expect(p).to.be.rejectedWith('third')
|
||||
})
|
||||
it('should resolve the value that first callback resolved', () => {
|
||||
let p = P.anySeries(['first', 'second'],
|
||||
const p = P.anySeries(['first', 'second'],
|
||||
item => Promise.resolve(item))
|
||||
return expect(p).to.eventually.equal('first')
|
||||
})
|
||||
it('should not call rest of callbacks once resolved', () => {
|
||||
let spy = sinon.spy()
|
||||
const spy = sinon.spy()
|
||||
return P
|
||||
.anySeries(['first', 'second'], (item, idx) => {
|
||||
if (idx > 0) {
|
||||
@@ -51,18 +51,18 @@ describe('util/promise', function () {
|
||||
})
|
||||
describe('.mapSeries()', function () {
|
||||
it('should resolve when all resolved', function () {
|
||||
let p = P.mapSeries(['first', 'second', 'third'],
|
||||
const p = P.mapSeries(['first', 'second', 'third'],
|
||||
item => Promise.resolve(item))
|
||||
return expect(p).to.eventually.deep.equal(['first', 'second', 'third'])
|
||||
})
|
||||
it('should reject with the error that first callback rejected', () => {
|
||||
let p = P.mapSeries(['first', 'second'],
|
||||
const p = P.mapSeries(['first', 'second'],
|
||||
item => Promise.reject(item))
|
||||
return expect(p).to.rejectedWith('first')
|
||||
})
|
||||
it('should resolve in series', function () {
|
||||
let spy1 = sinon.spy()
|
||||
let spy2 = sinon.spy()
|
||||
const spy1 = sinon.spy()
|
||||
const spy2 = sinon.spy()
|
||||
return P
|
||||
.mapSeries(
|
||||
['first', 'second'],
|
||||
@@ -80,7 +80,7 @@ describe('util/promise', function () {
|
||||
.then(() => expect(spy2).to.have.been.calledAfter(spy1))
|
||||
})
|
||||
it('should not call rest of callbacks once rejected', () => {
|
||||
let spy = sinon.spy()
|
||||
const spy = sinon.spy()
|
||||
return P
|
||||
.mapSeries(['first', 'second'], (item, idx) => {
|
||||
if (idx > 0) {
|
||||
|
||||
+13
-13
@@ -1,7 +1,7 @@
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
import chai from 'chai'
|
||||
import t from '../../src/util/strftime.js'
|
||||
|
||||
let t = require('../../src/util/strftime.js')
|
||||
const expect = chai.expect
|
||||
|
||||
describe('util/strftime', function () {
|
||||
let now
|
||||
@@ -37,7 +37,7 @@ describe('util/strftime', function () {
|
||||
expect(t(now, '%I')).to.equal('01')
|
||||
})
|
||||
it('should format %I as 12 for 00:00', function () {
|
||||
let date = new Date('2016-01-01T00:00:00.000Z')
|
||||
const date = new Date('2016-01-01T00:00:00.000Z')
|
||||
expect(t(date, '%I')).to.equal('12')
|
||||
})
|
||||
describe('%j', function () {
|
||||
@@ -45,11 +45,11 @@ describe('util/strftime', function () {
|
||||
expect(t(then, '%j')).to.equal('066')
|
||||
})
|
||||
it('should take count of leap years', function () {
|
||||
let date = new Date('2001-03-01')
|
||||
const date = new Date('2001-03-01')
|
||||
expect(t(date, '%j')).to.equal('060')
|
||||
})
|
||||
it('should take count of leap years', function () {
|
||||
let date = new Date('2000-03-01')
|
||||
const date = new Date('2000-03-01')
|
||||
expect(t(date, '%j')).to.equal('061')
|
||||
})
|
||||
})
|
||||
@@ -60,7 +60,7 @@ describe('util/strftime', function () {
|
||||
expect(t(now, '%l')).to.equal(' 1')
|
||||
})
|
||||
it('should format %l as 12 for 00:00', function () {
|
||||
let date = new Date('2016-01-01T00:00:00.000Z')
|
||||
const date = new Date('2016-01-01T00:00:00.000Z')
|
||||
expect(t(date, '%l')).to.equal('12')
|
||||
})
|
||||
it('should format %L as 0 padded millisecond', function () {
|
||||
@@ -75,9 +75,9 @@ describe('util/strftime', function () {
|
||||
expect(t(then, '%P')).to.equal('am')
|
||||
})
|
||||
it('should format %q as date suffix', function () {
|
||||
let st = new Date('2016-03-01T03:05:03.000Z')
|
||||
let nd = new Date('2016-03-02T03:05:03.000Z')
|
||||
let rd = new Date('2016-03-03T03:05:03.000Z')
|
||||
const st = new Date('2016-03-01T03:05:03.000Z')
|
||||
const nd = new Date('2016-03-02T03:05:03.000Z')
|
||||
const rd = new Date('2016-03-03T03:05:03.000Z')
|
||||
expect(t(st, '%q')).to.equal('st')
|
||||
expect(t(nd, '%q')).to.equal('nd')
|
||||
expect(t(rd, '%q')).to.equal('rd')
|
||||
@@ -113,7 +113,7 @@ describe('util/strftime', function () {
|
||||
expect(t(now, '%z')).to.equal('+0800')
|
||||
})
|
||||
it('should format %z as negative time zone', function () {
|
||||
let date = new Date('2016-01-04T13:15:23.000Z')
|
||||
const date = new Date('2016-01-04T13:15:23.000Z')
|
||||
date.getTimezoneOffset = () => 480
|
||||
expect(t(date, '%z')).to.equal('-0800')
|
||||
})
|
||||
@@ -126,7 +126,7 @@ describe('util/strftime', function () {
|
||||
})
|
||||
|
||||
function mockUTC () {
|
||||
let p = Date.prototype
|
||||
const p = Date.prototype
|
||||
|
||||
p._getHours = p.getHours
|
||||
p.getHours = p.getUTCHours
|
||||
@@ -139,7 +139,7 @@ function mockUTC () {
|
||||
}
|
||||
|
||||
function restoreUTC () {
|
||||
let p = Date.prototype
|
||||
const p = Date.prototype
|
||||
p.getHours = p._getHours
|
||||
p.getDays = p._getDays
|
||||
p.getTimezoneOffset = p._getTimezoneOffset
|
||||
|
||||
+12
-11
@@ -1,10 +1,11 @@
|
||||
import chai from 'chai'
|
||||
import sinonChai from 'sinon-chai'
|
||||
import sinon from 'sinon'
|
||||
import {RenderError, RenderBreakError} from '../../src/util/error.js'
|
||||
import _ from '../../src/util/underscore.js'
|
||||
import * as _ from '../../src/util/underscore.js'
|
||||
|
||||
const expect = chai.expect
|
||||
chai.use(require('sinon-chai'))
|
||||
chai.use(sinonChai)
|
||||
|
||||
describe('util/underscore', function () {
|
||||
describe('.isError()', function () {
|
||||
@@ -12,7 +13,7 @@ describe('util/underscore', function () {
|
||||
expect(_.isError(new Error())).to.be.true
|
||||
})
|
||||
it('should return true for RenderError', function () {
|
||||
let tpl = {
|
||||
const tpl = {
|
||||
token: {
|
||||
input: 'xx'
|
||||
}
|
||||
@@ -53,21 +54,21 @@ describe('util/underscore', function () {
|
||||
})
|
||||
describe('.forOwn()', function () {
|
||||
it('should iterate all properties', function () {
|
||||
let spy = sinon.spy()
|
||||
let obj = {
|
||||
const spy = sinon.spy()
|
||||
const obj = {
|
||||
foo: 'bar'
|
||||
}
|
||||
_.forOwn(obj, spy)
|
||||
expect(spy).to.have.been.calledWith('bar', 'foo', obj)
|
||||
})
|
||||
it('should default to empty object', function () {
|
||||
let spy = sinon.spy()
|
||||
const spy = sinon.spy()
|
||||
_.forOwn(undefined, spy)
|
||||
expect(spy).to.have.not.been.called
|
||||
})
|
||||
it('should not iterate over properties on prototype', function () {
|
||||
let spy = sinon.spy()
|
||||
let obj = Object.create({
|
||||
const spy = sinon.spy()
|
||||
const obj = Object.create({
|
||||
bar: 'foo'
|
||||
})
|
||||
obj.foo = 'bar'
|
||||
@@ -76,7 +77,7 @@ describe('util/underscore', function () {
|
||||
expect(spy).to.have.been.calledWith('bar', 'foo', obj)
|
||||
})
|
||||
it('should break when returned false', function () {
|
||||
let spy = sinon.stub().returns(false)
|
||||
const spy = sinon.stub().returns(false)
|
||||
_.forOwn({
|
||||
'foo': 'foo',
|
||||
'bar': 'foo'
|
||||
@@ -101,11 +102,11 @@ describe('util/underscore', function () {
|
||||
})
|
||||
})
|
||||
it('should assign 2 objects', function () {
|
||||
let src = {
|
||||
const src = {
|
||||
foo: 'foo',
|
||||
bar: 'bar'
|
||||
}
|
||||
let dst = {
|
||||
const dst = {
|
||||
foo: 'bar',
|
||||
kaa: 'kaa'
|
||||
}
|
||||
|
||||
+10
-12
@@ -1,4 +1,4 @@
|
||||
import {resolve} from '../../src/util/url.js'
|
||||
import {extname, resolve} from '../../src/util/url.js'
|
||||
import chai from 'chai'
|
||||
|
||||
const expect = chai.expect
|
||||
@@ -22,23 +22,23 @@ describe('util/url', function () {
|
||||
})
|
||||
describe('resolve', function () {
|
||||
describe('root', function () {
|
||||
it('should support width relative path', function () {
|
||||
it('should support relative root', function () {
|
||||
expect(resolve('./views', 'foo'))
|
||||
.to.equal('https://example.com/foo/bar/views/foo')
|
||||
expect(resolve('./views/', 'foo'))
|
||||
.to.equal('https://example.com/foo/bar/views/foo')
|
||||
})
|
||||
it('should support width absolute path', function () {
|
||||
it('should support absolute root', function () {
|
||||
expect(resolve('/views', 'foo'))
|
||||
.to.equal('https://example.com/views/foo')
|
||||
expect(resolve('/views/', 'foo'))
|
||||
.to.equal('https://example.com/views/foo')
|
||||
})
|
||||
it('should support with empty', function () {
|
||||
it('should support empty root', function () {
|
||||
expect(resolve('', 'page.html'))
|
||||
.to.equal('https://example.com/foo/bar/page.html')
|
||||
})
|
||||
it('should support with url', function () {
|
||||
it('should support full url as root', function () {
|
||||
expect(resolve('https://example.com/views', 'page.html'))
|
||||
.to.equal('https://example.com/views/page.html')
|
||||
expect(resolve('https://example.com/views/', 'page.html'))
|
||||
@@ -51,14 +51,12 @@ describe('util/url', function () {
|
||||
.to.equal('https://example.com/views/page.html')
|
||||
})
|
||||
})
|
||||
describe('path', function () {
|
||||
it('should support width relative path', function () {
|
||||
expect(resolve('./views/', 'page.html'))
|
||||
.to.equal('https://example.com/foo/bar/views/page.html')
|
||||
describe('extname', function () {
|
||||
it('should support relative path', function () {
|
||||
expect(extname('./views/page.html')).to.equal('.html')
|
||||
})
|
||||
it('should support with absolute path', function () {
|
||||
expect(resolve('/views/', '/page.html'))
|
||||
.to.equal('https://example.com/page.html')
|
||||
it('should support absolute path', function () {
|
||||
expect(extname('/views/page.xml')).to.equal('.xml')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user