refactor: es6 building and linting

This commit is contained in:
harttle
2018-08-16 23:14:12 +08:00
parent 5f634b0b5e
commit 19891b2df0
68 changed files with 1636 additions and 1575 deletions
+3
View File
@@ -0,0 +1,3 @@
{
"presets": ["es2015"]
}
+5 -1
View File
@@ -1,11 +1,15 @@
{
"extends": "standard",
"env": {
"es6": true,
"browser": true,
"node": true
},
"plugins": [
"standard",
"promise"
]
],
"rules": {
"no-var": 2
}
}
+8 -34
View File
@@ -1,40 +1,14 @@
# Logs
logs
# logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# tests
coverage/
.nyc_output/
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# modules
node_modules/
dist/
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules
jspm_packages
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
# vim
# editors
.*.swp
+1 -1
View File
@@ -6,4 +6,4 @@ node_js:
before_script:
- npm install -g mocha
after_script:
- npm run lcov && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage
- npm run coveralls
+1 -3
View File
@@ -10,19 +10,17 @@
<body>
<script>
var engine = window.Liquid({
// root: './',
extname: '.html',
cache: true
});
var src = '<h2>Welcome to {{ name | capitalize}}, ' +
'access time: {{date|date: "%Y-%m-%d %H:%M:%S"}}</h2>';
'access time: {{date|date: "%Y-%m-%d %H:%M:%S"}}&lt;/h2>';
var ctx = {
name: 'Liquid',
date: new Date()
};
engine.parseAndRender(src, ctx)
.then(function(html) {
document.body.innerHTML += html
return engine.renderFile('hello', ctx);
})
.then(function(html) {
+5 -5
View File
@@ -1,8 +1,8 @@
var express = require('express')
var app = express()
var Liquid = require('../..')
const express = require('express')
const Liquid = require('../..')
var engine = Liquid({
let app = express()
let engine = Liquid({
root: __dirname, // for layouts and partials
extname: '.liquid'
})
@@ -12,7 +12,7 @@ app.set('views', ['./partials', './views']) // specify the views directory
app.set('view engine', 'liquid') // set to default
app.get('/', function (req, res) {
var todos = ['fork and clone', 'make it better', 'make a pull request']
let todos = ['fork and clone', 'make it better', 'make a pull request']
res.render('todolist', {
todos: todos,
title: 'Welcome to liquidjs!'
+1 -1
View File
@@ -1,5 +1,5 @@
const app = require('./app.js')
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
console.log('Express running: http://localhost:3000')
})
+10
View File
@@ -0,0 +1,10 @@
const Liquid = require('../..')
let engine = new Liquid()
let src = 'Welcome to {{ name | capitalize}}, access time: {{date|date: "%H:%M:%S"}}'
let ctx = {
name: 'Liquid',
date: new Date()
}
engine.parseAndRender(src, ctx).then(console.log)
+1034 -970
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
File diff suppressed because one or more lines are too long
+13 -7
View File
@@ -2,15 +2,19 @@
"name": "liquidjs",
"version": "5.2.0",
"description": "Liquid template engine by pure JavaScript: compatible to shopify, easy to extend.",
"main": "src/index.js",
"main": "dist/index.js",
"scripts": {
"lint": "eslint .",
"test": "mocha --recursive",
"coverage": "cross-env NODE_ENV=test istanbul cover --report html ./node_modules/mocha/bin/_mocha -- -R spec --recursive",
"lcov": "cross-env NODE_ENV=test istanbul cover --report lcovonly ./node_modules/mocha/bin/_mocha -- -R spec --recursive",
"dist": "npm run browserify && npm run uglify",
"browserify": "browserify index.js -s Liquid --ignore path -t [ babelify --global true --presets [ es2015 ] ] > dist/liquid.js",
"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 dist",
"browserify": "browserify dist/index.js -s Liquid --ignore path --global true > dist/liquid.js",
"uglify": "uglifyjs dist/liquid.js --compress warnings=false --mangle --output dist/liquid.min.js",
"demo:browser": "echo open http://localhost:8080/demo/browser && http-server",
"demo:nodejs": "node ./demo/nodejs/index.js",
"demo:express": "cd ./demo/express/ && npm start",
"preversion": "npm run lint && npm test",
"version": "npm run dist && git add -A dist",
"postversion": "git push && git push --tags"
@@ -42,7 +46,7 @@
"fs": false
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-core": "^6.26.3",
"babel-preset-es2015": "^6.24.1",
"babelify": "^8.0.0",
"browserify": "^16.2.2",
@@ -58,10 +62,12 @@
"eslint-plugin-promise": "^3.5.0",
"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",
"sinon": "^6.1.4",
"sinon-chai": "^3.2.0",
"supertest": "^3.0.0",
+14 -14
View File
@@ -3,25 +3,25 @@ const Syntax = require('./syntax.js')
const assert = require('./util/assert.js')
const _ = require('./util/underscore.js')
var valueRE = new RegExp(`${lexical.value.source}`, 'g')
let valueRE = new RegExp(`${lexical.value.source}`, 'g')
module.exports = function (options) {
options = _.assign({}, options)
var filters = {}
let filters = {}
var _filterInstance = {
let _filterInstance = {
render: function (output, scope) {
var args = this.args.map(arg => Syntax.evalValue(arg, scope))
let args = this.args.map(arg => Syntax.evalValue(arg, scope))
args.unshift(output)
return this.filter.apply(null, args)
},
parse: function (str) {
var match = lexical.filterLine.exec(str)
let match = lexical.filterLine.exec(str)
assert(match, 'illegal filter: ' + str)
var name = match[1]
var argList = match[2] || ''
var filter = filters[name]
let name = match[1]
let argList = match[2] || ''
let 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
}
var args = []
let args = []
while ((match = valueRE.exec(argList.trim()))) {
var v = match[0]
var re = new RegExp(`${v}\\s*:`, 'g')
var keyMatch = re.exec(match.input)
var currentMatchIsKey = keyMatch && keyMatch.index === match.index
let v = match[0]
let re = new RegExp(`${v}\\s*:`, 'g')
let keyMatch = re.exec(match.input)
let currentMatchIsKey = keyMatch && keyMatch.index === match.index
currentMatchIsKey ? args.push(`'${v}'`) : args.push(v)
}
@@ -50,7 +50,7 @@ module.exports = function (options) {
}
function construct (str) {
var instance = Object.create(_filterInstance)
let instance = Object.create(_filterInstance)
return instance.parse(str)
}
+40 -39
View File
@@ -1,23 +1,22 @@
const Scope = require('./scope')
const _ = require('./util/underscore.js')
const assert = require('./util/assert.js')
const tokenizer = require('./tokenizer.js')
const statFileAsync = require('./util/fs.js').statFileAsync
const readFileAsync = require('./util/fs.js').readFileAsync
const path = require('path')
const url = require('./util/url.js')
const Render = require('./render.js')
const lexical = require('./lexical.js')
const Tag = require('./tag.js')
const Filter = require('./filter.js')
const Parser = require('./parser')
const Syntax = require('./syntax.js')
const tags = require('./tags')
const filters = require('./filters')
const anySeries = require('./util/promise.js').anySeries
const Errors = require('./util/error.js')
import Scope from './scope'
import _ from './util/underscore.js'
import assert from './util/assert.js'
import 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 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 Errors from './util/error.js'
var _engine = {
let _engine = {
init: function (tag, filter, options) {
if (options.cache) {
this.cache = {}
@@ -34,12 +33,12 @@ var _engine = {
return this
},
parse: function (html, filepath) {
var tokens = tokenizer.parse(html, filepath, this.options)
let tokens = tokenizer.parse(html, filepath, this.options)
return this.parser.parse(tokens)
},
render: function (tpl, ctx, opts) {
opts = _.assign({}, this.options, opts)
var scope = Scope.factory(ctx, opts)
let scope = Scope.factory(ctx, opts)
return this.renderer.renderTemplates(tpl, scope)
},
parseAndRender: function (html, ctx, opts) {
@@ -53,7 +52,7 @@ var _engine = {
.then(templates => this.render(templates, ctx, opts))
},
evalValue: function (str, scope) {
var tpl = this.parser.parseValue(str.trim())
let tpl = this.parser.parseValue(str.trim())
return this.renderer.evalValue(tpl, scope)
},
registerFilter: function (name, filter) {
@@ -65,7 +64,7 @@ var _engine = {
lookup: function (filepath, root) {
root = this.options.root.concat(root || [])
root = _.uniq(root)
var paths = root.map(root => path.resolve(root, filepath))
let paths = root.map(root => path.resolve(root, filepath))
return anySeries(paths, path => statFileAsync(path).then(() => path))
.catch((e) => {
e.message = `${e.code}: Failed to lookup ${filepath} in: ${root}`
@@ -85,7 +84,7 @@ var _engine = {
.lookup(filepath, root)
.then(filepath => {
if (this.options.cache) {
var tpl = this.cache[filepath]
let tpl = this.cache[filepath]
if (tpl) {
return Promise.resolve(tpl)
}
@@ -98,26 +97,26 @@ var _engine = {
})
},
getTemplateFromUrl: function (filepath, root) {
var fullUrl
if (url.valid(filepath)) {
let fullUrl
if (isValidUrl(filepath)) {
fullUrl = filepath
} else {
if (!url.extname(filepath)) {
if (!extname(filepath)) {
filepath += this.options.extname
}
fullUrl = url.resolve(root || this.options.root, filepath)
fullUrl = resolve(root || this.options.root, filepath)
}
if (this.options.cache) {
var tpl = this.cache[filepath]
let tpl = this.cache[filepath]
if (tpl) {
return Promise.resolve(tpl)
}
}
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest()
let xhr = new XMLHttpRequest()
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
var tpl = this.parse(xhr.responseText)
let tpl = this.parse(xhr.responseText)
if (this.options.cache) {
this.cache[filepath] = tpl
}
@@ -135,7 +134,7 @@ var _engine = {
},
express: function (opts) {
opts = opts || {}
var self = this
let self = this
return function (filePath, ctx, callback) {
assert(Array.isArray(this.root) || _.isString(this.root),
'illegal views root, are you using express.js?')
@@ -163,7 +162,7 @@ function factory (options) {
}, options)
options.root = normalizeStringArray(options.root)
var engine = Object.create(_engine)
let engine = Object.create(_engine)
engine.init(Tag(), Filter(options), options)
return engine
}
@@ -174,16 +173,18 @@ function normalizeStringArray (value) {
return []
}
factory.lexical = lexical
factory.isTruthy = Syntax.isTruthy
factory.isFalsy = Syntax.isFalsy
factory.evalExp = Syntax.evalExp
factory.evalValue = Syntax.evalValue
factory.Types = {
const Types = {
ParseError: Errors.ParseError,
TokenizationEroor: Errors.TokenizationError,
RenderBreakError: Errors.RenderBreakError,
AssertionError: Errors.AssertionError
}
factory.isTruthy = isTruthy
factory.isFalsy = isFalsy
factory.evalExp = evalExp
factory.evalValue = evalValue
factory.Types = Types
factory.lexical = lexical
module.exports = factory
+32 -32
View File
@@ -1,49 +1,49 @@
// quote related
var singleQuoted = /'[^']*'/
var doubleQuoted = /"[^"]*"/
var quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
var quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`)
let singleQuoted = /'[^']*'/
let doubleQuoted = /"[^"]*"/
let quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
let quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`)
// basic types
var integer = /-?\d+/
var number = /-?\d+\.?\d*|\.?\d+/
var bool = /true|false/
let integer = /-?\d+/
let number = /-?\d+\.?\d*|\.?\d+/
let bool = /true|false/
// peoperty access
var identifier = /[\w-]+[?]?/
var subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`)
var literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`)
var variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`)
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})*`)
// range related
var rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`)
var range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`)
var rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`)
let rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`)
let range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`)
let rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`)
var value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
let value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
// hash related
var hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`)
var hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
let hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`)
let hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
// full match
var tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`)
var literalLine = new RegExp(`^${literal.source}$`, 'i')
var variableLine = new RegExp(`^${variable.source}$`)
var numberLine = new RegExp(`^${number.source}$`)
var boolLine = new RegExp(`^${bool.source}$`, 'i')
var quotedLine = new RegExp(`^${quoted.source}$`)
var rangeLine = new RegExp(`^${rangeCapture.source}$`)
var integerLine = new RegExp(`^${integer.source}$`)
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}$`)
// filter related
var valueDeclaration = new RegExp(`(?:${identifier.source}\\s*:\\s*)?${value.source}`)
var valueList = new RegExp(`${valueDeclaration.source}(\\s*,\\s*${valueDeclaration.source})*`)
var filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g')
var filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`)
var filterLine = new RegExp(`^${filterCapture.source}$`)
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}$`)
var operators = [
let operators = [
/\s+or\s+/,
/\s+and\s+/,
/==|!=|<=|>=|<|>|\s+contains\s+/
@@ -70,7 +70,7 @@ function matchValue (str) {
}
function parseLiteral (str) {
var res = str.match(numberLine)
let res = str.match(numberLine)
if (res) {
return Number(str)
}
+11 -11
View File
@@ -3,7 +3,7 @@ const ParseError = require('./util/error.js').ParseError
const assert = require('./util/assert.js')
module.exports = function (Tag, Filter) {
var stream = {
let stream = {
init: function (tokens) {
this.tokens = tokens
this.handlers = {}
@@ -14,7 +14,7 @@ module.exports = function (Tag, Filter) {
return this
},
trigger: function (event, arg) {
var h = this.handlers[event]
let h = this.handlers[event]
if (typeof h === 'function') {
h(arg)
return true
@@ -22,14 +22,14 @@ module.exports = function (Tag, Filter) {
},
start: function () {
this.trigger('start')
var token
let token
while (!this.stopRequested && (token = this.tokens.shift())) {
if (this.trigger('token', token)) continue
if (token.type === 'tag' &&
this.trigger(`tag:${token.name}`, token)) {
continue
}
var template = parseToken(token, this.tokens)
let template = parseToken(token, this.tokens)
this.trigger('template', template)
}
if (!this.stopRequested) this.trigger('end')
@@ -42,8 +42,8 @@ module.exports = function (Tag, Filter) {
}
function parse (tokens) {
var token
var templates = []
let token
let templates = []
while ((token = tokens.shift())) {
templates.push(parseToken(token, tokens))
}
@@ -52,7 +52,7 @@ module.exports = function (Tag, Filter) {
function parseToken (token, tokens) {
try {
var tpl = null
let tpl = null
if (token.type === 'tag') {
tpl = parseTag(token, tokens)
} else if (token.type === 'value') {
@@ -73,13 +73,13 @@ module.exports = function (Tag, Filter) {
}
function parseValue (str) {
var match = lexical.matchValue(str)
let match = lexical.matchValue(str)
assert(match, `illegal value string: ${str}`)
var initial = match[0]
let initial = match[0]
str = str.substr(match.index + match[0].length)
var filters = []
let filters = []
while ((match = lexical.filter.exec(str))) {
filters.push([match[0].trim()])
}
@@ -92,7 +92,7 @@ module.exports = function (Tag, Filter) {
}
function parseStream (tokens) {
var s = Object.create(stream)
let s = Object.create(stream)
return s.init(tokens)
}
+3 -3
View File
@@ -5,12 +5,12 @@ const _ = require('./util/underscore.js')
const RenderError = require('./util/error.js').RenderError
const assert = require('./util/assert.js')
var render = {
let render = {
renderTemplates: function (templates, scope) {
assert(scope, 'unable to evalTemplates: scope undefined')
var html = ''
let html = ''
return mapSeries(templates, (tpl) => {
return renderTemplate.call(this, tpl)
.then(partial => (html += partial))
@@ -60,7 +60,7 @@ var render = {
}
function factory () {
var instance = Object.create(render)
let instance = Object.create(render)
return instance
}
+5 -5
View File
@@ -3,7 +3,7 @@ const _ = require('./util/underscore.js')
const lexical = require('./lexical.js')
const assert = require('./util/assert.js')
var Scope = {
let Scope = {
getAll: function () {
return this.contexts.reduce((ctx, val) => Object.assign(ctx, val), Object.create(null))
},
@@ -140,8 +140,8 @@ var Scope = {
}
function matchRightBracket (str, begin) {
var stack = 1 // count of '[' - count of ']'
for (var i = begin; i < str.length; i++) {
let stack = 1 // count of '[' - count of ']'
for (let i = begin; i < str.length; i++) {
if (str[i] === '[') {
stack++
}
@@ -156,14 +156,14 @@ function matchRightBracket (str, begin) {
}
exports.factory = function (ctx, opts) {
var defaultOptions = {
let defaultOptions = {
dynamicPartials: true,
strict_variables: false,
strict_filters: false,
blocks: {},
root: []
}
var scope = Object.create(Scope)
let scope = Object.create(Scope)
scope.opts = _.assign(defaultOptions, opts)
scope.contexts = [ctx || {}]
return scope
+13 -13
View File
@@ -1,27 +1,27 @@
const operators = require('./operators.js')(isTruthy)
const lexical = require('./lexical.js')
const assert = require('../src/util/assert.js')
const assert = require('./util/assert.js')
function evalExp (exp, scope) {
assert(scope, 'unable to evalExp: scope undefined')
var operatorREs = lexical.operators
var match
for (var i = 0; i < operatorREs.length; i++) {
var operatorRE = operatorREs[i]
var expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`)
let 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})$`)
if ((match = exp.match(expRE))) {
var l = evalExp(match[1], scope)
var op = operators[match[2].trim()]
var r = evalExp(match[3], scope)
let l = evalExp(match[1], scope)
let op = operators[match[2].trim()]
let r = evalExp(match[3], scope)
return op(l, r)
}
}
if ((match = exp.match(lexical.rangeLine))) {
var low = evalValue(match[1], scope)
var high = evalValue(match[2], scope)
var range = []
for (var j = low; j <= high; j++) {
let low = evalValue(match[1], scope)
let high = evalValue(match[2], scope)
let range = []
for (let j = low; j <= high; j++) {
range.push(j)
}
return range
+4 -5
View File
@@ -1,9 +1,8 @@
'use strict'
const Liquid = require('..')
const lexical = Liquid.lexical
import {lexical} from '../index'
import assert from '../util/assert.js'
import {types} from '../scope'
const re = new RegExp(`(${lexical.identifier.source})\\s*=(.*)`)
const assert = require('../util/assert.js')
const types = require('../scope').types
module.exports = function (liquid) {
liquid.registerTag('assign', {
+2 -2
View File
@@ -8,13 +8,13 @@ const types = require('../scope.js').types
module.exports = function (liquid) {
liquid.registerTag('capture', {
parse: function (tagToken, remainTokens) {
var match = tagToken.args.match(re)
let match = tagToken.args.match(re)
assert(match, `${tagToken.args} not valid identifier`)
this.variable = match[1]
this.templates = []
var stream = liquid.parser.parseStream(remainTokens)
let stream = liquid.parser.parseStream(remainTokens)
stream.on('tag:endcapture', token => stream.stop())
.on('template', tpl => this.templates.push(tpl))
.on('end', x => {
+7 -7
View File
@@ -1,4 +1,4 @@
const Liquid = require('..')
import Liquid from '..'
module.exports = function (liquid) {
liquid.registerTag('case', {
@@ -8,8 +8,8 @@ module.exports = function (liquid) {
this.cases = []
this.elseTemplates = []
var p = []
var stream = liquid.parser.parseStream(remainTokens)
let p = []
let stream = liquid.parser.parseStream(remainTokens)
.on('tag:when', token => {
this.cases.push({
val: token.args,
@@ -27,10 +27,10 @@ module.exports = function (liquid) {
},
render: function (scope, hash) {
for (var i = 0; i < this.cases.length; i++) {
var branch = this.cases[i]
var val = Liquid.evalExp(branch.val, scope)
var cond = Liquid.evalExp(this.cond, scope)
for (let i = 0; i < this.cases.length; i++) {
let branch = this.cases[i]
let val = Liquid.evalExp(branch.val, scope)
let cond = Liquid.evalExp(this.cond, scope)
if (val === cond) {
return liquid.renderer.renderTemplates(branch.templates, scope)
}
+1 -1
View File
@@ -1,7 +1,7 @@
module.exports = function (liquid) {
liquid.registerTag('comment', {
parse: function (tagToken, remainTokens) {
var stream = liquid.parser.parseStream(remainTokens)
let stream = liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
if (token.name === 'endcomment') stream.stop()
+7 -7
View File
@@ -8,11 +8,11 @@ module.exports = function (liquid) {
liquid.registerTag('cycle', {
parse: function (tagToken, remainTokens) {
var match = groupRE.exec(tagToken.args)
let match = groupRE.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.group = match[1] || ''
var candidates = match[2]
let candidates = match[2]
this.candidates = []
@@ -23,17 +23,17 @@ module.exports = function (liquid) {
},
render: function (scope, hash) {
var group = Liquid.evalValue(this.group, scope)
var fingerprint = `cycle:${group}:` + this.candidates.join(',')
let group = Liquid.evalValue(this.group, scope)
let fingerprint = `cycle:${group}:` + this.candidates.join(',')
var groups = scope.opts.groups = scope.opts.groups || {}
var idx = groups[fingerprint]
let groups = scope.opts.groups = scope.opts.groups || {}
let idx = groups[fingerprint]
if (idx === undefined) {
idx = groups[fingerprint] = 0
}
var candidate = this.candidates[idx]
let candidate = this.candidates[idx]
idx = (idx + 1) % this.candidates.length
groups[fingerprint] = idx
+1 -1
View File
@@ -7,7 +7,7 @@ const types = require('../scope').types
module.exports = function (liquid) {
liquid.registerTag('decrement', {
parse: function (token) {
var match = token.args.match(lexical.identifier)
let match = token.args.match(lexical.identifier)
assert(match, `illegal identifier ${token.args}`)
this.variable = match[0]
},
+14 -14
View File
@@ -1,9 +1,9 @@
const Liquid = require('..')
const lexical = Liquid.lexical
const mapSeries = require('../util/promise.js').mapSeries
const _ = require('../util/underscore.js')
import {default as Liquid, lexical} from '../index'
import {mapSeries} from '../util/promise.js'
import _ from '../util/underscore.js'
import assert from '../util/assert.js'
const RenderBreakError = Liquid.Types.RenderBreakError
const assert = require('../util/assert.js')
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
`(${lexical.value.source})` +
`(?:\\s+${lexical.hash.source})*` +
@@ -14,7 +14,7 @@ module.exports = function (liquid) {
liquid.registerTag('for', {
parse: function (tagToken, remainTokens) {
var match = re.exec(tagToken.args)
let match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1]
this.collection = match[2]
@@ -23,8 +23,8 @@ module.exports = function (liquid) {
this.templates = []
this.elseTemplates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
let p
let stream = liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates))
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endfor', () => stream.stop())
@@ -37,7 +37,7 @@ module.exports = function (liquid) {
},
render: function (scope, hash) {
var collection = Liquid.evalExp(this.collection, scope)
let collection = Liquid.evalExp(this.collection, scope)
if (!Array.isArray(collection)) {
if (_.isString(collection) && collection.length > 0) {
@@ -50,14 +50,14 @@ module.exports = function (liquid) {
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
var offset = hash.offset || 0
var limit = (hash.limit === undefined) ? collection.length : hash.limit
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()
var contexts = collection.map((item, i) => {
var ctx = {}
let contexts = collection.map((item, i) => {
let ctx = {}
ctx[this.variable] = item
ctx.forloop = {
first: i === 0,
@@ -71,7 +71,7 @@ module.exports = function (liquid) {
return ctx
})
var html = ''
let html = ''
return mapSeries(contexts, (context) => {
return Promise.resolve()
.then(() => scope.push(context))
+6 -6
View File
@@ -1,4 +1,4 @@
const Liquid = require('..')
import Liquid from '..'
module.exports = function (liquid) {
liquid.registerTag('if', {
@@ -7,8 +7,8 @@ module.exports = function (liquid) {
this.branches = []
this.elseTemplates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
let p
let stream = liquid.parser.parseStream(remainTokens)
.on('start', () => this.branches.push({
cond: tagToken.args,
templates: (p = [])
@@ -30,9 +30,9 @@ module.exports = function (liquid) {
},
render: function (scope, hash) {
for (var i = 0; i < this.branches.length; i++) {
var branch = this.branches[i]
var cond = Liquid.evalExp(branch.cond, scope)
for (let i = 0; i < this.branches.length; i++) {
let branch = this.branches[i]
let cond = Liquid.evalExp(branch.cond, scope)
if (Liquid.isTruthy(cond)) {
return liquid.renderer.renderTemplates(branch.templates, scope)
}
+4 -4
View File
@@ -12,7 +12,7 @@ const staticFileRE = /\S+/
module.exports = function (liquid) {
liquid.registerTag('layout', {
parse: function (token, remainTokens) {
var match = staticFileRE.exec(token.args)
let match = staticFileRE.exec(token.args)
if (match) {
this.staticLayout = match[0]
}
@@ -25,7 +25,7 @@ module.exports = function (liquid) {
this.tpls = liquid.parser.parse(remainTokens)
},
render: function (scope, hash) {
var layout = scope.opts.dynamicPartials ? Liquid.evalValue(this.layout, scope) : this.staticLayout
let layout = scope.opts.dynamicPartials ? Liquid.evalValue(this.layout, scope) : this.staticLayout
assert(layout, `cannot apply layout with empty filename`)
// render the remaining tokens immediately
@@ -51,11 +51,11 @@ module.exports = function (liquid) {
liquid.registerTag('block', {
parse: function (token, remainTokens) {
var match = /\w+/.exec(token.args)
let match = /\w+/.exec(token.args)
this.block = match ? match[0] : ''
this.tpls = []
var stream = liquid.parser.parseStream(remainTokens)
let stream = liquid.parser.parseStream(remainTokens)
.on('tag:endblock', () => stream.stop())
.on('template', tpl => this.tpls.push(tpl))
.on('end', () => {
+1 -1
View File
@@ -3,7 +3,7 @@ module.exports = function (liquid) {
parse: function (tagToken, remainTokens) {
this.tokens = []
var stream = liquid.parser.parseStream(remainTokens)
let stream = liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
if (token.name === 'endraw') stream.stop()
+16 -15
View File
@@ -1,7 +1,8 @@
const Liquid = require('..')
const mapSeries = require('../util/promise.js').mapSeries
import Liquid from '..'
import {mapSeries} from '../util/promise.js'
import assert from '../util/assert.js'
const lexical = Liquid.lexical
const assert = require('../util/assert.js')
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
`(${lexical.value.source})` +
`(?:\\s+${lexical.hash.source})*$`)
@@ -10,15 +11,15 @@ module.exports = function (liquid) {
liquid.registerTag('tablerow', {
parse: function (tagToken, remainTokens) {
var match = re.exec(tagToken.args)
let match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1]
this.collection = match[2]
this.templates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
let p
let stream = liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates))
.on('tag:endtablerow', token => stream.stop())
.on('template', tpl => p.push(tpl))
@@ -30,21 +31,21 @@ module.exports = function (liquid) {
},
render: function (scope, hash) {
var collection = Liquid.evalExp(this.collection, scope) || []
let collection = Liquid.evalExp(this.collection, scope) || []
var html = ''
var offset = hash.offset || 0
var limit = (hash.limit === undefined) ? collection.length : hash.limit
let html = ''
let offset = hash.offset || 0
let limit = (hash.limit === undefined) ? collection.length : hash.limit
var cols = hash.cols
var row
var col
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
var contexts = collection.map((item, i) => {
var ctx = {}
let contexts = collection.map((item, i) => {
let ctx = {}
ctx[this.variable] = item
return ctx
})
+4 -4
View File
@@ -1,12 +1,12 @@
const Liquid = require('..')
import Liquid from '../index'
module.exports = function (liquid) {
liquid.registerTag('unless', {
parse: function (tagToken, remainTokens) {
this.templates = []
this.elseTemplates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
let p
let stream = liquid.parser.parseStream(remainTokens)
.on('start', x => {
p = this.templates
this.cond = tagToken.args
@@ -22,7 +22,7 @@ module.exports = function (liquid) {
},
render: function (scope, hash) {
var cond = Liquid.evalExp(this.cond, scope)
let cond = Liquid.evalExp(this.cond, scope)
return Liquid.isFalsy(cond)
? liquid.renderer.renderTemplates(this.templates, scope)
: liquid.renderer.renderTemplates(this.elseTemplates, scope)
+12 -12
View File
@@ -7,13 +7,13 @@ const assert = require('./util/assert.js')
function parse (input, file, options) {
assert(_.isString(input), 'illegal input')
var rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
var currIndent = 0
var lineNumber = LineNumber(input)
var lastMatchEnd = 0
var tokens = []
let rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
let currIndent = 0
let lineNumber = LineNumber(input)
let lastMatchEnd = 0
let tokens = []
for (var match; (match = rLiquid.exec(input)); lastMatchEnd = rLiquid.lastIndex) {
for (let match; (match = rLiquid.exec(input)); lastMatchEnd = rLiquid.lastIndex) {
if (match.index > lastMatchEnd) {
tokens.push(parseHTMLToken(lastMatchEnd, match.index))
}
@@ -28,8 +28,8 @@ function parse (input, file, options) {
return tokens
function parseTagToken (raw, value, pos) {
var match = value.match(lexical.tagLine)
var token = {
let match = value.match(lexical.tagLine)
let token = {
type: 'tag',
indent: currIndent,
line: lineNumber.get(pos),
@@ -62,7 +62,7 @@ function parse (input, file, options) {
}
function parseHTMLToken (begin, end) {
var htmlFragment = input.slice(begin, end)
let htmlFragment = input.slice(begin, end)
currIndent = _.last((htmlFragment).split('\n')).length
return {
@@ -74,12 +74,12 @@ function parse (input, file, options) {
}
function LineNumber (html) {
var parsedLinesCount = 0
var lastMatchBegin = -1
let parsedLinesCount = 0
let lastMatchBegin = -1
return {
get: function (pos) {
var lines = html.slice(lastMatchBegin + 1, pos).split('\n')
let lines = html.slice(lastMatchBegin + 1, pos).split('\n')
parsedLinesCount += lines.length - 1
lastMatchBegin = pos
return parsedLinesCount + 1
+9 -9
View File
@@ -1,4 +1,4 @@
const _ = require('./underscore.js')
import _ 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
var context = mkContext(token.input, token.line)
let 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) {
var lines = input.split('\n')
var begin = Math.max(line - 2, 1)
var end = Math.min(line + 3, lines.length)
let lines = input.split('\n')
let begin = Math.max(line - 2, 1)
let end = Math.min(line + 3, lines.length)
var context = _
let context = _
.range(begin, end + 1)
.map(l => [
(l === line) ? '>> ' : ' ',
@@ -82,9 +82,9 @@ function mkContext (input, line) {
}
function align (n, max) {
var length = (max + '').length
var str = n + ''
var blank = Array(length - str.length).join(' ')
let length = (max + '').length
let str = n + ''
let blank = Array(length - str.length).join(' ')
return blank + str
}
+3 -3
View File
@@ -5,7 +5,7 @@
* The iteratee is invoked with three arguments: (value, index, iterable).
*/
function anySeries (iterable, iteratee) {
var ret = Promise.reject(new Error('init'))
let ret = Promise.reject(new Error('init'))
iterable.forEach(function (item, idx) {
ret = ret.catch(e => iteratee(item, idx, iterable))
})
@@ -19,8 +19,8 @@ function anySeries (iterable, iteratee) {
* The iteratee is invoked with three arguments: (value, index, iterable).
*/
function mapSeries (iterable, iteratee) {
var ret = Promise.resolve('init')
var result = []
let ret = Promise.resolve('init')
let result = []
iterable.forEach(function (item, idx) {
ret = ret
.then(() => iteratee(item, idx, iterable))
+27 -27
View File
@@ -1,16 +1,16 @@
var monthNames = [
let monthNames = [
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'
]
var monthNamesShort = [
let monthNamesShort = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
'Nov', 'Dec'
]
var dayNames = [
let dayNames = [
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
]
var dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
var suffixes = {
let dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
let suffixes = {
1: 'st',
2: 'nd',
3: 'rd',
@@ -18,15 +18,15 @@ var suffixes = {
}
// prototype extensions
var _date = {
let _date = {
daysInMonth: function (d) {
var feb = _date.isLeapYear(d) ? 29 : 28
let feb = _date.isLeapYear(d) ? 29 : 28
return [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
},
getDayOfYear: function (d) {
var num = 0
for (var i = 0; i < d.getMonth(); ++i) {
let num = 0
for (let i = 0; i < d.getMonth(); ++i) {
num += _date.daysInMonth(d)[i]
}
return num + d.getDate()
@@ -36,21 +36,21 @@ var _date = {
// TODO: that comment was retarted. fix it.
getWeekOfYear: function (d, startDay) {
// Skip to startDay of this week
var now = this.getDayOfYear(d) + (startDay - d.getDay())
let now = this.getDayOfYear(d) + (startDay - d.getDay())
// Find the first startDay of the year
var jan1 = new Date(d.getFullYear(), 0, 1)
var then = (7 - jan1.getDay() + startDay)
let jan1 = new Date(d.getFullYear(), 0, 1)
let then = (7 - jan1.getDay() + startDay)
return _number.pad(Math.floor((now - then) / 7) + 1, 2)
},
isLeapYear: function (d) {
var year = d.getFullYear()
let year = d.getFullYear()
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)))
},
getSuffix: function (d) {
var str = d.getDate().toString()
var index = parseInt(str.slice(-1))
let str = d.getDate().toString()
let index = parseInt(str.slice(-1))
return suffixes[index] || suffixes['default']
},
@@ -59,11 +59,11 @@ var _date = {
}
}
var _number = {
let _number = {
pad: function (value, size, ch) {
if (!ch) ch = '0'
var result = value.toString()
var pad = size - result.length
let result = value.toString()
let pad = size - result.length
while (pad-- > 0) {
result = ch + result
@@ -73,7 +73,7 @@ var _number = {
}
}
var formatCodes = {
let formatCodes = {
a: function (d) {
return dayNamesShort[d.getDay()]
},
@@ -162,7 +162,7 @@ var formatCodes = {
return d.getFullYear()
},
z: function (d) {
var tz = d.getTimezoneOffset() / 60 * 100
let tz = d.getTimezoneOffset() / 60 * 100
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4)
},
'%': function () {
@@ -172,13 +172,13 @@ var formatCodes = {
formatCodes.h = formatCodes.b
formatCodes.N = formatCodes.L
var strftime = function (d, format) {
var output = ''
var remaining = format
let strftime = function (d, format) {
let output = ''
let remaining = format
while (true) {
var r = /%./g
var results = r.exec(remaining)
let r = /%./g
let results = r.exec(remaining)
// No more format codes. Add the remaining text and return
if (!results) {
@@ -190,8 +190,8 @@ var strftime = function (d, format) {
remaining = remaining.slice(r.lastIndex)
// Add the format code
var ch = results[0].charAt(1)
var func = formatCodes[ch]
let ch = results[0].charAt(1)
let func = formatCodes[ch]
output += func ? func.call(this, d) : '%' + ch
}
}
+9 -10
View File
@@ -1,4 +1,3 @@
'use strict'
const toStr = Object.prototype.toString
/*
@@ -46,7 +45,7 @@ function isArray (value) {
}
function isError (value) {
var signature = Object.prototype.toString.call(value)
let signature = Object.prototype.toString.call(value)
// [object XXXError]
return signature.substr(-6, 5) === 'Error' ||
(typeof value.message === 'string' && typeof value.name === 'string')
@@ -62,7 +61,7 @@ function isError (value) {
*/
function forOwn (object, iteratee) {
object = object || {}
for (var k in object) {
for (let k in object) {
if (object.hasOwnProperty(k)) {
if (iteratee(object[k], k, object) === false) break
}
@@ -83,7 +82,7 @@ function forOwn (object, iteratee) {
*/
function assign (object) {
object = isObject(object) ? object : {}
var srcs = Array.prototype.slice.call(arguments, 1)
let srcs = Array.prototype.slice.call(arguments, 1)
srcs.forEach((src) => Object.assign(object, src))
return object
}
@@ -93,9 +92,9 @@ function last (arr) {
}
function uniq (arr) {
var u = {}
var a = []
for (var i = 0, l = arr.length; i < l; ++i) {
let u = {}
let a = []
for (let i = 0, l = arr.length; i < l; ++i) {
if (u.hasOwnProperty(arr[i])) {
continue
}
@@ -112,7 +111,7 @@ function uniq (arr) {
* @return {Boolean} Returns true if value is an object, else false.
*/
function isObject (value) {
var type = typeof value
let type = typeof value
return value != null && (type === 'object' || type === 'function')
}
@@ -131,8 +130,8 @@ function range (start, stop, step) {
}
step = step || 1
var arr = []
for (var i = start; i < stop; i += step) {
let arr = []
for (let i = start; i < stop; i += step) {
arr.push(i)
}
return arr
+7 -6
View File
@@ -1,24 +1,25 @@
const resolve = require('resolve-url')
import resolveUrl from 'resolve-url'
import _ from './underscore'
const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/
const urlRe = /^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[:?\d]*)\S*$/
const _ = require('./underscore')
// https://github.com/jinder/path/blob/master/path.js#L567
exports.extname = function (path) {
export function extname (path) {
return splitPathRe.exec(path).slice(1)[3]
}
// https://www.npmjs.com/package/is-url
exports.valid = function (path) {
export function valid (path) {
return urlRe.test(path)
}
exports.resolve = function (root, path) {
export function resolve (root, path) {
if (Object.prototype.toString.call(root) === '[object Array]') {
root = root[0]
}
if (root && _.last(root) !== '/') {
root += '/'
}
return resolve(root, path)
return resolveUrl(root, path)
}
+3 -3
View File
@@ -2,7 +2,7 @@ const _ = require('./util/underscore.js')
function whiteSpaceCtrl (tokens, options) {
options = _.assign({ greedy: true }, options)
var inRaw = false
let inRaw = false
tokens.forEach((token, i) => {
if (shouldTrimLeft(token, inRaw, options)) {
@@ -33,14 +33,14 @@ function shouldTrimRight (token, inRaw, options) {
function trimLeft (token, greedy) {
if (!token || token.type !== 'html') return
var rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
let rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
token.value = token.value.replace(rLeft, '')
}
function trimRight (token, greedy) {
if (!token || token.type !== 'html') return
var rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
let rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
token.value = token.value.replace(rRight, '')
}
+5 -5
View File
@@ -6,7 +6,7 @@ const express = require('express')
const Liquid = require('../src')
describe('engine#express()', function () {
var app, engine
let app, engine
beforeEach(function () {
app = express()
@@ -36,11 +36,11 @@ describe('engine#express()', function () {
.expect(200, done)
})
it('should pass error when file not found', function (done) {
var view = {
let view = {
root: []
}
var file = '/not-exist.html'
var ctx = {}
let file = '/not-exist.html'
let ctx = {}
engine.express().call(view, file, ctx, function (err) {
try {
expect(err.code).to.equal('ENOENT')
@@ -82,7 +82,7 @@ describe('engine#express()', function () {
.expect(200, done)
})
it('should respect express views (Undefined) when lookup', function (done) {
var files = {}
let files = {}
files[process.cwd() + '/views/include.html'] = '{% include file %}'
files[process.cwd() + '/views/bar.html'] = 'bar'
mock(files)
+11 -11
View File
@@ -5,17 +5,17 @@ const expect = chai.expect
chai.use(sinonChai)
var filter = require('../src/filter.js')()
var Scope = require('../src/scope.js')
let filter = require('../src/filter.js')()
let Scope = require('../src/scope.js')
describe('filter', function () {
var scope
let scope
beforeEach(function () {
filter.clear()
scope = Scope.factory()
})
it('should return default filter when not registered', function () {
var result = filter.construct('foo')
let 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)
var f = filter.construct('foo: a, "b"')
let 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 () {
var spy = sinon.spy()
let 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)
var f = filter.construct('foo: key1: "literal1", key2: value2')
let f = filter.construct('foo: key1: "literal1", key2: value2')
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal([ '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
})
it('should support arguments as named key/values with inline literals', function () {
filter.register('foo', x => x)
var f = filter.construct('foo: "test0", key1: "literal1", key2: value2')
let f = filter.construct('foo: "test0", key1: "literal1", key2: value2')
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal([ '"test0"', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
})
it('should support arguments as named key/values with inline values', function () {
filter.register('foo', x => x)
var f = filter.construct('foo: test0, key1: "literal1", key2: value2')
let f = filter.construct('foo: test0, key1: "literal1", key2: value2')
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal([ 'test0', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
})
it('should support argument values named same as keys', function () {
filter.register('foo', x => x)
var f = filter.construct('foo: a: a')
let f = filter.construct('foo: a: a')
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal(['\'a\'', 'a'])
})
it('should support argument literals named same as keys', function () {
filter.register('foo', x => x)
var f = filter.construct('foo: a: "a"')
let f = filter.construct('foo: a: "a"')
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal(['\'a\'', '"a"'])
})
+16 -14
View File
@@ -1,10 +1,12 @@
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const expect = chai.expect
var liquid = require('../src')()
chai.use(chaiAsPromised)
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import Liquid from '../src/index'
var ctx = {
chai.use(chaiAsPromised)
const liquid = new Liquid()
const expect = chai.expect
let ctx = {
date: new Date(),
foo: 'bar',
arr: [-2, 'a'],
@@ -83,7 +85,7 @@ describe('filters', function () {
describe('date', function () {
it('should support date: %a %b %d %Y', function () {
var str = ctx.date.toDateString()
let str = ctx.date.toDateString()
return test('{{ date | date:"%a %b %d %Y"}}', str)
})
it('should create a new Date when given "now"', function () {
@@ -128,7 +130,7 @@ describe('filters', function () {
return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara')
})
it('should escape function', function () {
return test('{{ func | escape }}', 'function () {}')
return test('{{ func | escape }}', 'function func() {}')
})
})
@@ -140,7 +142,7 @@ describe('filters', function () {
})
it('should support split/first', function () {
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
let src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}'
return test(src, 'apples')
})
@@ -153,19 +155,19 @@ describe('filters', function () {
})
it('should support join', function () {
var src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
let src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
'{{ beatles | join: " and " }}'
return test(src, 'John and Paul and George and Ringo')
})
it('should support split/last', function () {
var src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
let src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
'{{ my_array|last }}'
return test(src, 'tiger')
})
it('should support lstrip', function () {
var src = '{{ " So much room for activities! " | lstrip }}'
let src = '{{ " So much room for activities! " | lstrip }}'
return test(src, 'So much room for activities! ')
})
@@ -191,12 +193,12 @@ describe('filters', function () {
})
it('should support string_with_newlines', function () {
var src = '{% capture string_with_newlines %}\n' +
let src = '{% capture string_with_newlines %}\n' +
'Hello\n' +
'there\n' +
'{% endcapture %}' +
'{{ string_with_newlines | newline_to_br }}'
var dst = '<br />' +
let dst = '<br />' +
'Hello<br />' +
'there<br />'
return test(src, dst)
+7 -7
View File
@@ -5,7 +5,7 @@ const mock = require('mock-fs')
chai.use(require('chai-as-promised'))
describe('liquid', function () {
var engine, strictEngine, ctx
let engine, strictEngine, ctx
beforeEach(function () {
ctx = {
name: 'harttle',
@@ -37,7 +37,7 @@ describe('liquid', function () {
})
describe('Liquid', function () {
it('should ignore invalid root option', function () {
var liquid = Liquid({ root: /regex/ })
let liquid = Liquid({ root: /regex/ })
expect(liquid.options.root).to.deep.equal([])
})
})
@@ -68,18 +68,18 @@ describe('liquid', function () {
}).to.not.throw()
})
it('should render template multiple times', function () {
var template = engine.parse('{{obj}}')
let template = engine.parse('{{obj}}')
return engine.render(template, ctx)
.then(result => expect(result).to.equal('{"foo":"bar"}'))
.then(() => engine.render(template, ctx))
.then((result) => expect(result).to.equal('{"foo":"bar"}'))
})
it('should render filters', function () {
var template = engine.parse('<p>{{arr | join: "_"}}</p>')
let template = engine.parse('<p>{{arr | join: "_"}}</p>')
return expect(engine.render(template, ctx)).to.eventually.equal('<p>-2_a</p>')
})
it('should render accessive filters', function () {
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
let src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}'
return expect(engine.parseAndRender(src)).to.eventually.equal('apples')
})
@@ -89,7 +89,7 @@ describe('liquid', function () {
.to.eventually.equal('foo')
})
it('should find files without extname', function () {
var engine = Liquid({root: '/root'})
let engine = Liquid({root: '/root'})
return expect(engine.renderFile('/root/files/bar', ctx))
.to.eventually.equal('bar')
})
@@ -106,7 +106,7 @@ describe('liquid', function () {
.to.eventually.equal('foo')
})
it('should default root to cwd', function () {
var files = {}
let files = {}
files[process.cwd() + '/foo.html'] = 'FOO'
mock(files)
+6 -6
View File
@@ -1,7 +1,7 @@
const chai = require('chai')
const expect = chai.expect
var lexical = require('../src/lexical.js')
let lexical = require('../src/lexical.js')
describe('lexical', function () {
it('should test filter syntax', function () {
@@ -105,26 +105,26 @@ describe('lexical', function () {
})
it('should throw if non-literal', function () {
var fn = () => lexical.parseLiteral('a')
let fn = () => lexical.parseLiteral('a')
expect(fn).to.throw("cannot parse 'a' as literal")
})
})
describe('.matchValue()', function () {
it('should match -5-5', function () {
var match = lexical.matchValue('-5-5')
let match = lexical.matchValue('-5-5')
expect(match && match[0]).to.equal('-5-5')
})
it('should match 4-3', function () {
var match = lexical.matchValue('4-3')
let match = lexical.matchValue('4-3')
expect(match && match[0]).to.equal('4-3')
})
it('should match 4-3', function () {
var match = lexical.matchValue('4-3')
let match = lexical.matchValue('4-3')
expect(match && match[0]).to.equal('4-3')
})
it('should match var-1', function () {
var match = lexical.matchValue('var-1')
let match = lexical.matchValue('var-1')
expect(match && match[0]).to.equal('var-1')
})
})
+1 -1
View File
@@ -5,7 +5,7 @@ const Liquid = require('../../src')
chai.use(require('chai-as-promised'))
describe('cache options', function () {
var engine
let engine
beforeEach(function () {
engine = Liquid({
root: '/root/',
+6 -6
View File
@@ -4,8 +4,8 @@ const Liquid = require('../../src')
chai.use(require('chai-as-promised'))
describe('strict options', function () {
var engine
var ctx = {}
let engine
let ctx = {}
beforeEach(function () {
engine = Liquid({
root: '/root/',
@@ -17,16 +17,16 @@ describe('strict options', function () {
.eventually.equal('beforeafter')
})
it('should throw when strict_variables true', function () {
var tpl = engine.parse('before{{notdefined}}after')
var opts = {
let tpl = engine.parse('before{{notdefined}}after')
let opts = {
strict_variables: true
}
return expect(engine.render(tpl, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/)
})
it('should pass strict_variables to render by parseAndRender', function () {
var html = 'before{{notdefined}}after'
var opts = {
let html = 'before{{notdefined}}after'
let opts = {
strict_variables: true
}
return expect(engine.parseAndRender(html, ctx, opts)).to
+16 -16
View File
@@ -4,59 +4,59 @@ const Liquid = require('../../src')
chai.use(require('chai-as-promised'))
describe('trimming', function () {
var ctx = {name: 'harttle'}
let ctx = {name: 'harttle'}
describe('tag trimming', function () {
it('should respect trim_tag_left', function () {
var engine = Liquid({ trim_tag_left: true })
let engine = Liquid({ trim_tag_left: true })
return expect(engine.parseAndRender(' \n \t{%if true%}foo{%endif%} '))
.to.eventually.equal('foo ')
})
it('should respect trim_tag_right', function () {
var engine = Liquid({ trim_tag_right: true })
let engine = Liquid({ trim_tag_right: true })
return expect(engine.parseAndRender('\t{%if true%}foo{%endif%} \n'))
.to.eventually.equal('\tfoo')
})
it('should not trim value', function () {
var engine = Liquid({ trim_tag_left: true, trim_tag_right: true })
let engine = Liquid({ trim_tag_left: true, trim_tag_right: true })
return expect(engine.parseAndRender('{%if true%}a {{name}} b{%endif%}', ctx))
.to.eventually.equal('a harttle b')
})
})
describe('value trimming', function () {
it('should respect trim_value_left', function () {
var engine = Liquid({ trim_value_left: true })
let engine = Liquid({ trim_value_left: true })
return expect(engine.parseAndRender(' \n \t{{name}} ', ctx))
.to.eventually.equal('harttle ')
})
it('should respect trim_value_right', function () {
var engine = Liquid({ trim_value_right: true })
let engine = Liquid({ trim_value_right: true })
return expect(engine.parseAndRender(' \n \t{{name}} ', ctx))
.to.eventually.equal(' \n \tharttle')
})
it('should respect not trim tag', function () {
var engine = Liquid({ trim_value_left: true, trim_value_right: true })
let engine = Liquid({ trim_value_left: true, trim_value_right: true })
return expect(engine.parseAndRender('\t{% if true %} aha {%endif%}\t'))
.to.eventually.equal('\t aha \t')
})
})
describe('greedy', function () {
var src = '\n {%-if true-%}\n a \n{{-name-}}{%-endif-%}\n '
let src = '\n {%-if true-%}\n a \n{{-name-}}{%-endif-%}\n '
it('should enable greedy by default', function () {
var engine = Liquid()
let engine = Liquid()
return expect(engine.parseAndRender(src, ctx))
.to.eventually.equal('aharttle')
})
it('should respect to greedy:false by default', function () {
var engine = Liquid({greedy: false})
let engine = Liquid({greedy: false})
return expect(engine.parseAndRender(src, ctx))
.to.eventually.equal('\n a \nharttle ')
})
})
describe('markup', function () {
it('should support trim using markup', function () {
var engine = Liquid()
var src = [
let engine = Liquid()
let src = [
'{%- assign username = "John G. Chalmers-Smith" -%}',
'{%- if username and username.length > 10 -%}',
' Wow, {{ username }}, you have a long name!',
@@ -64,12 +64,12 @@ describe('trimming', function () {
' Hello there!',
'{%- endif -%}'
].join('\n')
var dst = 'Wow, John G. Chalmers-Smith, you have a long name!'
let dst = 'Wow, John G. Chalmers-Smith, you have a long name!'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
})
it('should not trim when not specified', function () {
var engine = Liquid()
var src = [
let engine = Liquid()
let src = [
'{% assign username = "John G. Chalmers-Smith" %}',
'{% if username and username.length > 10 %}',
' Wow, {{ username }}, you have a long name!',
@@ -77,7 +77,7 @@ describe('trimming', function () {
' Hello there!',
'{% endif %}'
].join('\n')
var dst = '\n\n Wow, John G. Chalmers-Smith, you have a long name!\n'
let dst = '\n\n Wow, John G. Chalmers-Smith, you have a long name!\n'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
})
})
+8 -8
View File
@@ -3,13 +3,13 @@ const expect = chai.expect
chai.use(require('sinon-chai'))
var filter = require('../src/filter.js')()
var tag = require('../src/tag.js')()
var Template = require('../src/parser.js')
let filter = require('../src/filter.js')()
let tag = require('../src/tag.js')()
let Template = require('../src/parser.js')
describe('template', function () {
var template
var add = (l, r) => l + r
let template
let add = (l, r) => l + r
beforeEach(function () {
filter.clear()
@@ -26,21 +26,21 @@ describe('template', function () {
})
it('should parse value string', function () {
var tpl = template.parseValue('foo')
let 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 () {
var tpl = template.parseValue('foo | add: 3, "foo"')
let 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 () {
var tpl = template.parseValue('foo | add: "|" | add')
let tpl = template.parseValue('foo | add: "|" | add')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters.length).to.equal(2)
})
+5 -6
View File
@@ -1,11 +1,10 @@
'use strict'
const chai = require('chai')
import chai from 'chai'
import Scope from '../src/scope.js'
const expect = chai.expect
var Scope = require('../src/scope.js')
describe('scope', function () {
var scope, ctx
let scope, ctx
beforeEach(function () {
ctx = {
foo: 'zoo',
@@ -161,7 +160,7 @@ describe('scope', function () {
})
})
describe('strict_variables', function () {
var scope
let scope
beforeEach(function () {
scope = Scope.factory(ctx, {
strict_variables: true
+7 -7
View File
@@ -1,14 +1,14 @@
const chai = require('chai')
const expect = chai.expect
var syntax = require('../src/syntax.js')
var Scope = require('../src/scope.js')
let syntax = require('../src/syntax.js')
let Scope = require('../src/scope.js')
var evalExp = syntax.evalExp
var evalValue = syntax.evalValue
var isTruthy = syntax.isTruthy
let evalExp = syntax.evalExp
let evalValue = syntax.evalValue
let isTruthy = syntax.isTruthy
describe('expression', function () {
var scope
let scope
beforeEach(function () {
scope = Scope.factory({
@@ -36,7 +36,7 @@ describe('expression', function () {
})
it('should throw if not valid', function () {
var fn = () => evalValue('===')
let fn = () => evalValue('===')
expect(fn).to.throw("cannot eval '===' as value")
})
})
+5 -5
View File
@@ -3,11 +3,11 @@ const sinon = require('sinon')
const expect = chai.expect
chai.use(require('sinon-chai'))
var tag = require('../src/tag.js')()
var Scope = require('../src/scope.js')
let tag = require('../src/tag.js')()
let Scope = require('../src/scope.js')
describe('tag', function () {
var scope
let scope
before(function () {
scope = Scope.factory({
foo: 'bar',
@@ -38,7 +38,7 @@ describe('tag', function () {
})
it('should call tag.render', function () {
var spy = sinon.spy()
let spy = sinon.spy()
tag.register('foo', {
render: spy
})
@@ -53,7 +53,7 @@ describe('tag', function () {
})
describe('hash', function () {
var spy, token
let spy, token
beforeEach(function () {
spy = sinon.spy()
tag.register('foo', {
+8 -8
View File
@@ -4,46 +4,46 @@ const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/case', function () {
var liquid = Liquid()
let liquid = Liquid()
it('should reject if not closed', function () {
var src = '{% case "foo"%}'
let src = '{% case "foo"%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% case "foo"%} not closed/)
})
it('should hit the specified case', function () {
var src = '{% case "foo"%}' +
let 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 () {
var src = '{% case empty %}' +
let src = '{% case empty %}' +
'{% when "foo" %}foo{% when ""%}bar' +
'{%endcase%}'
var ctx = {
let ctx = {
empty: ''
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('bar')
})
it('should accept empty string as branch name', function () {
var src = '{% case false %}' +
let src = '{% case false %}' +
'{% when "foo" %}foo{% when ""%}bar' +
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
it('should support boolean case', function () {
var src = '{% case false %}' +
let src = '{% case false %}' +
'{% when "foo" %}foo{% when false%}bar' +
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('bar')
})
it('should support else branch', function () {
var src = '{% case "a" %}' +
let src = '{% case "a" %}' +
'{% when "b" %}b{% when "c"%}c{%else %}d' +
'{%endcase%}'
return expect(liquid.parseAndRender(src))
+6 -6
View File
@@ -4,29 +4,29 @@ const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/comment', function () {
var liquid = Liquid()
let liquid = Liquid()
it('should support empty content', function () {
var src = '{% comment %}{% raw%}'
let src = '{% comment %}{% raw%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% comment %} not closed/)
})
it('should ignore plain string', function () {
var src = 'My name is {% comment %}super{% endcomment %} Shopify.'
let src = 'My name is {% comment %}super{% endcomment %} Shopify.'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('My name is Shopify.')
})
it('should ignore output tokens', function () {
var src = '{% comment %}\n{{ foo}} \n{% endcomment %}'
let src = '{% comment %}\n{{ foo}} \n{% endcomment %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
it('should ignore tag tokens', function () {
var src = '{% comment %}{%if true%}true{%else%}false{%endif%}{% endcomment %}'
let src = '{% comment %}{%if true%}true{%else%}false{%endif%}{% endcomment %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
it('should ignore un-balenced tag tokens', function () {
var src = '{% comment %}{%if true%}true{%else%}false{% endcomment %}'
let src = '{% comment %}{%if true%}true{%else%}false{% endcomment %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
+6 -6
View File
@@ -4,10 +4,10 @@ const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/cycle', function () {
var liquid = Liquid()
let liquid = Liquid()
it('should support cycle', function () {
var src = "{% cycle '1', '2', '3' %}"
let src = "{% cycle '1', '2', '3' %}"
return expect(liquid.parseAndRender(src + src + src + src))
.to.eventually.equal('1231')
})
@@ -18,8 +18,8 @@ describe('tags/cycle', function () {
})
it('should support cycle in for block', function () {
var src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}'
var ctx = {
let src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}'
let ctx = {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
@@ -27,10 +27,10 @@ describe('tags/cycle', function () {
})
it('should support cycle group', function () {
var src = "{% cycle one: '1', '2', '3'%}" +
let src = "{% cycle one: '1', '2', '3'%}" +
"{% cycle 1: '1', '2', '3'%}" +
"{% cycle 2: '1', '2', '3'%}"
var ctx = {
let ctx = {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
+3 -3
View File
@@ -5,10 +5,10 @@ const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/decrement', function () {
var liquid = Liquid()
let liquid = Liquid()
it('should throw when variable expression illegal', function () {
var src = '{% decrement / %}{{var}}'
var ctx = {}
let src = '{% decrement / %}{{var}}'
let ctx = {}
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/)
})
+29 -29
View File
@@ -4,7 +4,7 @@ const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/for', function () {
var liquid, ctx
let liquid, ctx
before(function () {
liquid = Liquid()
liquid.registerTag('throwingTag', {
@@ -22,25 +22,25 @@ describe('tags/for', function () {
}
})
it('should support array', function () {
var src = '{%for c in alpha%}{{c}}{%endfor%}'
let src = '{%for c in alpha%}{{c}}{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('abc')
})
it('should support object', function () {
var src = '{%for item in obj%}{{item[0]}},{{item[1]}}-{%else%}b{%endfor%}'
let 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 () {
var src = '{%for a in (1..2)%}{{num}}{%endfor%}'
let src = '{%for a in (1..2)%}{{num}}{%endfor%}'
return expect(liquid.parseAndRender(src, {num: 1}))
.to.eventually.equal('11')
})
it('should write super scope', function () {
var src = '{%for a in (1..2)%}{{num}}{%assign num = 2%}{%endfor%}'
let src = '{%for a in (1..2)%}{{num}}{%assign num = 2%}{%endfor%}'
return expect(liquid.parseAndRender(src, {num: 1}))
.to.eventually.equal('12')
})
@@ -48,13 +48,13 @@ describe('tags/for', function () {
describe('illegal', function () {
it('should reject when for not closed', function () {
var src = '{%for c in alpha%}{{c}}'
let src = '{%for c in alpha%}{{c}}'
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag .* not closed/)
})
it('should reject when inner templates rejected', function () {
var src = '{%for c in alpha%}{%throwingTag%}{%endfor%}'
let src = '{%for c in alpha%}{%throwingTag%}{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/intended render error/)
})
@@ -62,51 +62,51 @@ describe('tags/for', function () {
describe('else', function () {
it('should goto else for empty array', function () {
var src = '{%for c in emptyArray%}a{%else%}b{%endfor%}'
let src = '{%for c in emptyArray%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should treat non-empty string as one single element', function () {
var src = '{%for c in "abc"%}x{{c}}{%else%}y{%endfor%}'
let src = '{%for c in "abc"%}x{{c}}{%else%}y{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('xabc')
})
it('should goto else for empty string', function () {
var src = '{%for c in ""%}a{%else%}b{%endfor%}'
let src = '{%for c in ""%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should goto else for empty string object', function () {
// it should be false although `new String` is none-conform
var src = '{%for c in strObj%}a{%else%}b{%endfor%}'
let src = '{%for c in strObj%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should goto else for empty object', function () {
var src = '{%for c in emptyObj%}a{%else%}b{%endfor%}'
let src = '{%for c in emptyObj%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should goto else for null-prototyped object', function () {
var src = '{%for c in nullProtoObj%}a{%else%}b{%endfor%}'
let src = '{%for c in nullProtoObj%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
})
it('should support for with forloop', function () {
var src = '{%for c in alpha%}' +
let src = '{%for c in alpha%}' +
'{{forloop.first}}.{{forloop.index}}.{{forloop.index0}}.' +
'{{forloop.last}}.{{forloop.length}}.' +
'{{forloop.rindex}}.{{forloop.rindex0}}' +
'{{c}}\n' +
'{%endfor%}'
var dst = 'true.1.0.false.3.3.2a\n' +
let 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))
@@ -114,14 +114,14 @@ describe('tags/for', function () {
})
it('should support for with continue', function () {
var src = '{% for i in (1..5) %}' +
let src = '{% for i in (1..5) %}' +
'{{i}}{% continue %}after' +
'{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12345')
})
it('should support for with break', function () {
var src = '{% for i in (one..5) %}' +
let src = '{% for i in (one..5) %}' +
'{% if i == 4 %}{% break %}{% endif %}' +
'{{ i }}' +
'{% endfor %}'
@@ -131,22 +131,22 @@ describe('tags/for', function () {
describe('limit', function () {
it('should support for with limit', function () {
var src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}'
let src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12')
})
it('should set forloop.last properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.last}} {%endfor%}'
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.last}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('false true ')
})
it('should set forloop.first properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.first}} {%endfor%}'
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.first}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('true false ')
})
it('should set forloop.length properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.length}} {%endfor%}'
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.length}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2 2 ')
})
@@ -154,27 +154,27 @@ describe('tags/for', function () {
describe('offset', function () {
it('should support offset with limit', function () {
var src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}'
let src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('67')
})
it('should set index properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index}} {%endfor%}'
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1 2 ')
})
it('should set index0 properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index0}} {%endfor%}'
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index0}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('0 1 ')
})
it('should set rindex properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex}} {%endfor%}'
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2 1 ')
})
it('should set rindex0 properly', function () {
var src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex0}} {%endfor%}'
let src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex0}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1 0 ')
})
@@ -182,19 +182,19 @@ describe('tags/for', function () {
describe('reverse', function () {
it('should support for reversed in the last position', function () {
var src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}'
let src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21')
})
it('should support for reversed in the first position', function () {
var src = '{% for i in (1..5) reversed limit:2 %}{{ i }}{% endfor %}'
let src = '{% for i in (1..5) reversed limit:2 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21')
})
it('should support for reversed in the middle position', function () {
var src = '{% for i in (1..5) offset:2 reversed limit:4 %}{{ i }}{% endfor %}'
let 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
View File
@@ -4,8 +4,8 @@ const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/if', function () {
var liquid = Liquid()
var ctx = {
let liquid = Liquid()
let ctx = {
one: 1,
two: 2,
emptyString: '',
@@ -13,101 +13,101 @@ describe('tags/if', function () {
}
it('should throw if not closed', function () {
var src = '{% if false%}yes'
let src = '{% if false%}yes'
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag {% if false%} not closed/)
})
it('should support nested', function () {
var src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}'
let src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('')
})
describe('single value as condition', function () {
it('should support boolean', function () {
var src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}'
let src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2')
})
it('should treat Array truthy', function () {
var src = '{%if emptyArray%}a{%endif%}'
let src = '{%if emptyArray%}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a')
})
it('should return true if empty string', function () {
var src = '{%if emptyString%}a{%endif%}'
let src = '{%if emptyString%}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a')
})
})
describe('expression as condition', function () {
it('should support ==', function () {
var src = '{% if 2==3 %}yes{%else%}no{%endif%}'
let src = '{% if 2==3 %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should support >=', function () {
var src = '{% if 1>=2 and one<two %}a{%endif%}'
let src = '{% if 1>=2 and one<two %}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('')
})
it('should support !=', function () {
var src = '{% if one!=two %}yes{%else%}no{%endif%}'
let src = '{% if one!=two %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('yes')
})
it('should support value and expression', function () {
var src = `X{%if version and version != '' %}x{{version}}y{%endif%}Y`
var ctx = { 'version': '' }
let src = `X{%if version and version != '' %}x{{version}}y{%endif%}Y`
let ctx = { 'version': '' }
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('XY')
})
})
describe('comparasion to null', function () {
it('should evaluate false for null < 10', function () {
var src = '{% if null < 10 %}yes{% else %}no{% endif %}'
let src = '{% if null < 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for null > 10', function () {
var src = '{% if null > 10 %}yes{% else %}no{% endif %}'
let src = '{% if null > 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for null <= 10', function () {
var src = '{% if null <= 10 %}yes{% else %}no{% endif %}'
let src = '{% if null <= 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for null >= 10', function () {
var src = '{% if null >= 10 %}yes{% else %}no{% endif %}'
let src = '{% if null >= 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for 10 < null', function () {
var src = '{% if 10 < null %}yes{% else %}no{% endif %}'
let src = '{% if 10 < null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for 10 > null', function () {
var src = '{% if 10 > null %}yes{% else %}no{% endif %}'
let src = '{% if 10 > null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for 10 <= null', function () {
var src = '{% if 10 <= null %}yes{% else %}no{% endif %}'
let src = '{% if 10 <= null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for 10 >= null', function () {
var src = '{% if 10 >= null %}yes{% else %}no{% endif %}'
let src = '{% if 10 >= null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
+6 -6
View File
@@ -5,7 +5,7 @@ const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/include', function () {
var liquid
let liquid
before(function () {
liquid = Liquid({
root: '/',
@@ -94,7 +94,7 @@ describe('tags/include', function () {
'/card.html': '<p>{{person.firstName}} {{person.lastName}}<br/>{% include "address" %}</p>',
'/address.html': 'City: {{person.address.city}}'
})
var ctx = {
let ctx = {
person: {
firstName: 'Joe',
lastName: 'Shmoe',
@@ -113,7 +113,7 @@ describe('tags/include', function () {
'/parent.html': 'X{% include child.html color:"red" %}Y',
'/child.html': 'child with {{color}}'
})
var staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
let staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
return expect(staticLiquid.renderFile('parent.html')).to
.eventually.equal('Xchild with redY')
})
@@ -123,7 +123,7 @@ describe('tags/include', function () {
'/parent.html': 'X{% include bar/./../foo/child.html %}Y',
'/foo/child.html': 'child'
})
var staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
let staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
return expect(staticLiquid.renderFile('parent.html')).to
.eventually.equal('XchildY')
})
@@ -133,7 +133,7 @@ describe('tags/include', function () {
'/parent.html': 'X{% include foo/child.html %}Y',
'/foo/child.html': 'child'
})
var staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
let staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
return expect(staticLiquid.renderFile('parent.html')).to
.eventually.equal('XchildY')
})
@@ -143,7 +143,7 @@ describe('tags/include', function () {
'/parent.html': 'X{% include child.html, color:"red" %}Y',
'/child.html': 'child with {{color}}'
})
var staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
let staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
return expect(staticLiquid.renderFile('parent.html')).to
.eventually.equal('Xchild with redY')
})
+9 -9
View File
@@ -5,7 +5,7 @@ const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/layout', function () {
var liquid
let liquid
before(function () {
liquid = Liquid({
root: '/',
@@ -20,7 +20,7 @@ describe('tags/layout', function () {
mock({
'/parent.html': 'parent'
})
var src = '{% layout "parent" %}{%block%}A'
let src = '{% layout "parent" %}{%block%}A'
return expect(liquid.parseAndRender(src)).to
.be.rejectedWith(/tag {%block%} not closed/)
})
@@ -38,7 +38,7 @@ describe('tags/layout', function () {
mock({
'/parent.html': 'X{%block%}{%endblock%}Y'
})
var src = '{% layout "parent.html" %}{%block%}A{%endblock%}'
let src = '{% layout "parent.html" %}{%block%}A{%endblock%}'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAY')
})
@@ -46,7 +46,7 @@ describe('tags/layout', function () {
mock({
'/parent.html': 'X{%block%}{%endblock%}Y'
})
var src = '{% layout "parent.html" %}A'
let src = '{% layout "parent.html" %}A'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAY')
})
@@ -55,7 +55,7 @@ describe('tags/layout', function () {
mock({
'/parent.html': 'X{% block "a"%}{% endblock %}Y{% block b%}{%endblock%}Z'
})
var src = '{% layout "parent.html" %}' +
let src = '{% layout "parent.html" %}' +
'{%block a%}A{%endblock%}' +
'{%block b%}B{%endblock%}'
return expect(liquid.parseAndRender(src)).to
@@ -65,7 +65,7 @@ describe('tags/layout', function () {
mock({
'/parent.html': 'X{% block "a"%}A{% endblock %}Y{% block b%}B{%endblock%}Z'
})
var src = '{% layout "parent.html" %}{%block a%}a{%endblock%}'
let src = '{% layout "parent.html" %}{%block a%}a{%endblock%}'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XaYBZ')
})
@@ -112,7 +112,7 @@ describe('tags/layout', function () {
'/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout parent.html color:"black"%}{%block%}A{%endblock%}'
})
var staticLiquid = Liquid({ root: '/', dynamicPartials: false })
let staticLiquid = Liquid({ root: '/', dynamicPartials: false })
return expect(staticLiquid.renderFile('/main.html')).to
.eventually.equal('blackA')
})
@@ -122,7 +122,7 @@ describe('tags/layout', function () {
'/foo/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout bar/../foo/parent.html color:"black"%}{%block%}A{%endblock%}'
})
var staticLiquid = Liquid({ root: '/', dynamicPartials: false })
let staticLiquid = Liquid({ root: '/', dynamicPartials: false })
return expect(staticLiquid.renderFile('/main.html')).to
.eventually.equal('blackA')
})
@@ -132,7 +132,7 @@ describe('tags/layout', function () {
'/foo/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout foo/parent.html color:"black"%}{%block%}A{%endblock%}'
})
var staticLiquid = Liquid({ root: '/', dynamicPartials: false })
let staticLiquid = Liquid({ root: '/', dynamicPartials: false })
return expect(staticLiquid.renderFile('/main.html')).to
.eventually.equal('blackA')
})
+5 -5
View File
@@ -4,20 +4,20 @@ const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/raw', function () {
var liquid = Liquid()
let liquid = Liquid()
it('should support raw 1', function () {
return expect(liquid.parseAndRender('{% raw%}'))
.to.be.rejectedWith(/{% raw%} not closed/)
})
it('should support raw 2', function () {
var src = '{% raw %}{{ 5 | plus: 6 }}{% endraw %} is equal to 11.'
var dst = '{{ 5 | plus: 6 }} is equal to 11.'
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 3', function () {
var src = '{% raw %}\n{{ foo}} \n{% endraw %}'
var dst = '\n{{ foo}} \n'
let src = '{% raw %}\n{{ foo}} \n{% endraw %}'
let dst = '\n{{ foo}} \n'
return expect(liquid.parseAndRender(src))
.to.eventually.equal(dst)
})
+19 -19
View File
@@ -4,52 +4,52 @@ const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/tablerow', function () {
var liquid = Liquid()
let liquid = Liquid()
it('should support tablerow', function () {
var src = '{% tablerow i in (1..3)%}{{ i }}{% endtablerow %}'
var dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>'
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>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support cols', function () {
var src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}'
var ctx = {
let src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}'
let ctx = {
alpha: ['a', 'b', 'c']
}
var dst =
let 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 () {
var src = '{% tablerow i in (1..3) cols:0 %}{{ i }}{% endtablerow %}'
var dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>'
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>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support empty tablerow', function () {
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}'
var dst = ''
let src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}'
let dst = ''
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support empty array', function () {
var src = '{% tablerow i in alpha.z cols:2 %}{{ i }}{% endtablerow %}'
var dst = ''
let src = '{% tablerow i in alpha.z cols:2 %}{{ i }}{% endtablerow %}'
let dst = ''
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should throw when tablerow not closed', function () {
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}'
let src = '{% tablerow i in (1..0) cols:2 %}{{ i }}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/)
})
it('should support tablerow with range', function () {
var src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}'
var dst =
let src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}'
let 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>'
@@ -57,16 +57,16 @@ describe('tags/tablerow', function () {
})
it('should support tablerow with limit', function () {
var src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}'
var dst =
let src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}'
let dst =
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
'<tr class="row2"><td class="col1">3</td></tr>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support tablerow with offset', function () {
var src = '{% tablerow i in (1..5) cols:2 offset:3 %}{{ i }}{% endtablerow %}'
var dst = '<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>'
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>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
})
+6 -6
View File
@@ -4,31 +4,31 @@ const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/unless', function () {
var liquid = Liquid()
let liquid = Liquid()
it('should render else when predicate yields true', function () {
// 0 is truthy
var src = '{% unless 0 %}yes{%else%}no{%endunless%}'
let src = '{% unless 0 %}yes{%else%}no{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('no')
})
it('should render unless when predicate yields false', function () {
var src = '{% unless false %}yes{%else%}no{%endunless%}'
let src = '{% unless false %}yes{%else%}no{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes')
})
it('should reject when tag not closed', function () {
var src = '{% unless 1>2 %}yes'
let src = '{% unless 1>2 %}yes'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag {% unless 1>2 %} not closed/)
})
it('should render unless when predicate yields false and else undefined', function () {
var src = '{% unless 1>2 %}yes{%endunless%}'
let src = '{% unless 1>2 %}yes{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes')
})
it('should render "" when predicate yields false and else undefined', function () {
var src = '{% unless 1<2 %}yes{%endunless%}'
let src = '{% unless 1<2 %}yes{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
+14 -14
View File
@@ -5,8 +5,8 @@ const expect = chai.expect
describe('tokenizer', function () {
describe('parse', function () {
it('should handle plain HTML', function () {
var html = '<html><body><p>Lorem Ipsum</p></body></html>'
var tokens = parse(html)
let html = '<html><body><p>Lorem Ipsum</p></body></html>'
let 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 () {
var html = '<p>{% for p in a[1]%}</p>'
var tokens = parse(html)
let html = '<p>{% for p in a[1]%}</p>'
let 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 () {
var html = '<p>{{foo | date: "%Y-%m-%d"}}</p>'
var tokens = parse(html)
let html = '<p>{{foo | date: "%Y-%m-%d"}}</p>'
let 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 () {
var html = '{{foo}}{{bar}}{%foo%}{%bar%}'
var tokens = parse(html)
let html = '{{foo}}{{bar}}{%foo%}{%bar%}'
let 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 () {
var html = '{%foo%}\n{%bar %} \n {%alice%}'
var tokens = parse(html)
let html = '{%foo%}\n{%bar %} \n {%alice%}'
let 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 () {
var html = '{%foo\na:a\nb:1.23\n%}'
var tokens = parse(html)
let html = '{%foo\na:a\nb:1.23\n%}'
let tokens = parse(html)
expect(tokens.length).to.equal(1)
expect(tokens[0].type).to.equal('tag')
expect(tokens[0].args).to.equal('a:a\nb:1.23')
expect(tokens[0].raw).to.equal('{%foo\na:a\nb:1.23\n%}')
})
it('should handle multiple lines value', function () {
var html = '{{foo\n|date:\n"%Y-%m-%d"\n}}'
var tokens = parse(html)
let html = '{{foo\n|date:\n"%Y-%m-%d"\n}}'
let 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}}')
+3 -3
View File
@@ -4,15 +4,15 @@ const assert = require('../../src/util/assert.js')
describe('assert', function () {
it('should not throw if predicate is truthy', function () {
var fn = () => assert('foo', 'bar')
let fn = () => assert('foo', 'bar')
expect(fn).to.not.throw()
})
it('should not throw if predicate is truthy', function () {
var fn = () => assert('', 'bar')
let fn = () => assert('', 'bar')
expect(fn).to.throw(/bar/)
})
it('should populate default message', function () {
var fn = () => assert(false)
let fn = () => assert(false)
expect(fn).to.throw(/expect false to be true/)
})
})
+28 -28
View File
@@ -4,8 +4,8 @@ const mock = require('mock-fs')
const path = require('path')
chai.use(require('chai-as-promised'))
var engine = require('../..')()
var strictEngine = require('../..')({
let engine = require('../..')()
let strictEngine = require('../..')({
strict_variables: true,
strict_filters: true
})
@@ -25,8 +25,8 @@ describe('error', function () {
})
})
it('should contain template content in err.message', function () {
var html = ['1st', '2nd', 'X{% . a %} Y', '4th']
var message = [
let html = ['1st', '2nd', 'X{% . a %} Y', '4th']
let message = [
' 1| 1st',
' 2| 2nd',
'>> 3| X{% . a %} Y',
@@ -42,7 +42,7 @@ describe('error', function () {
})
})
it('should contain the whole template content in err.input', function () {
var html = 'bar\nfoo{% . a %}\nfoo'
let html = 'bar\nfoo{% . a %}\nfoo'
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function (err) {
@@ -66,7 +66,7 @@ describe('error', function () {
})
})
describe('captureStackTrace compatibility', function () {
var captureStackTrace = Error.captureStackTrace
let captureStackTrace = Error.captureStackTrace
before(() => (Error.captureStackTrace = null))
after(() => (Error.captureStackTrace = captureStackTrace))
it('should use empty string if captureStackTrace not defined', function () {
@@ -79,7 +79,7 @@ describe('error', function () {
})
})
it('should contain file path in err.file', function () {
var html = '<html>\n<head>\n\n{% . a %}\n\n'
let html = '<html>\n<head>\n\n{% . a %}\n\n'
mock({
'/foo.html': html
})
@@ -113,7 +113,7 @@ describe('error', function () {
})
})
it('should throw RenderError when tag throws', function () {
var src = '{%throwingTag%}'
let src = '{%throwingTag%}'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function (err) {
@@ -122,7 +122,7 @@ describe('error', function () {
})
})
it('should throw RenderError when tag rejects', function () {
var src = '{%rejectingTag%}'
let src = '{%rejectingTag%}'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function (err) {
@@ -131,7 +131,7 @@ describe('error', function () {
})
})
it('should throw RenderError when filter throws', function () {
var src = '{{1|throwingFilter}}'
let src = '{{1|throwingFilter}}'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function (err) {
@@ -151,8 +151,8 @@ describe('error', function () {
})
})
it('should contain template context in err.stack', function () {
var html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
var message = [
let html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
let message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
@@ -181,8 +181,8 @@ describe('error', function () {
'7th'
].join('\n')
})
var html = '{%layout "throwing-tag.html"%}'
var message = [
let html = '{%layout "throwing-tag.html"%}'
let message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
@@ -202,12 +202,12 @@ describe('error', function () {
})
})
it('should contain original error info for {% include %}', function () {
var origin = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
let origin = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
mock({
'/throwing-tag.html': origin.join('\n')
})
var html = '{%include "throwing-tag.html"%}'
var message = [
let html = '{%include "throwing-tag.html"%}'
let message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
@@ -225,7 +225,7 @@ describe('error', function () {
})
})
it('should contain the whole template content in err.input', function () {
var html = 'bar\nfoo{%throwingTag%}\nfoo'
let html = 'bar\nfoo{%throwingTag%}\nfoo'
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function (err) {
@@ -234,7 +234,7 @@ describe('error', function () {
})
})
it('should contain line number in err.line', function () {
var src = '1\n2\n{{1|throwingFilter}}\n4'
let src = '1\n2\n{{1|throwingFilter}}\n4'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function (err) {
@@ -252,7 +252,7 @@ describe('error', function () {
})
it('should contain file path in err.file', function () {
var html = '<html>\n<head>\n\n{% throwingTag %}\n\n'
let html = '<html>\n<head>\n\n{% throwingTag %}\n\n'
mock({
'/foo.html': html
})
@@ -293,7 +293,7 @@ describe('error', function () {
})
})
it('should throw ParseError when tag parse throws', function () {
var src = '{%throwsOnParse%}'
let src = '{%throwsOnParse%}'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function (err) {
@@ -302,7 +302,7 @@ describe('error', function () {
})
})
it('should throw ParseError when tag not found', function () {
var src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3'
let src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function (err) {
@@ -321,8 +321,8 @@ describe('error', function () {
})
it('should contain template context in err.stack', function () {
var html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th']
var message = [
let html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th']
let message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{% a %} {% enda %} Y',
@@ -341,8 +341,8 @@ describe('error', function () {
})
it('should handle err.message when context not enough', function () {
var html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th']
var message = [
let html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th']
let message = [
' 1| 1st',
'>> 2| X{% a %} {% enda %} Y',
' 3| 3rd',
@@ -358,7 +358,7 @@ describe('error', function () {
})
it('should contain line number in err.line', function () {
var html = '<html>\n<head>\n\n{% raw %}\n\n'
let html = '<html>\n<head>\n\n{% raw %}\n\n'
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function (err) {
@@ -376,7 +376,7 @@ describe('error', function () {
})
it('should contain file path in err.file', function () {
var html = '<html>\n<head>\n\n{% raw %}\n\n'
let html = '<html>\n<head>\n\n{% raw %}\n\n'
mock({
'/foo.html': html
})
+11 -11
View File
@@ -4,13 +4,13 @@ const expect = chai.expect
chai.use(require('chai-as-promised'))
chai.use(require('sinon-chai'))
var P = require('../../src/util/promise.js')
let P = require('../../src/util/promise.js')
describe('util/promise', function () {
describe('.anySeries()', function () {
it('should resolve in series', function () {
var spy1 = sinon.spy()
var spy2 = sinon.spy()
let spy1 = sinon.spy()
let 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 () {
var p = P.anySeries(['first', 'second', 'third'],
let p = P.anySeries(['first', 'second', 'third'],
item => Promise.reject(new Error(item)))
return expect(p).to.be.rejectedWith('third')
})
it('should resolve the value that first callback resolved', () => {
var p = P.anySeries(['first', 'second'],
let p = P.anySeries(['first', 'second'],
item => Promise.resolve(item))
return expect(p).to.eventually.equal('first')
})
it('should not call rest of callbacks once resolved', () => {
var spy = sinon.spy()
let 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 () {
var p = P.mapSeries(['first', 'second', 'third'],
let p = P.mapSeries(['first', 'second', 'third'],
item => Promise.resolve(item))
return expect(p).to.eventually.deep.equal(['first', 'second', 'third'])
})
it('should reject with the error that first callback rejected', () => {
var p = P.mapSeries(['first', 'second'],
let p = P.mapSeries(['first', 'second'],
item => Promise.reject(item))
return expect(p).to.rejectedWith('first')
})
it('should resolve in series', function () {
var spy1 = sinon.spy()
var spy2 = sinon.spy()
let spy1 = sinon.spy()
let 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', () => {
var spy = sinon.spy()
let spy = sinon.spy()
return P
.mapSeries(['first', 'second'], (item, idx) => {
if (idx > 0) {
+13 -13
View File
@@ -1,11 +1,11 @@
const chai = require('chai')
const expect = chai.expect
var t = require('../../src/util/strftime.js')
let t = require('../../src/util/strftime.js')
describe('util/strftime', function () {
var now
var then
let now
let then
before(function () {
mockUTC()
now = new Date('2016-01-04T13:15:23.000Z')
@@ -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 () {
var date = new Date('2016-01-01T00:00:00.000Z')
let 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 () {
var date = new Date('2001-03-01')
let date = new Date('2001-03-01')
expect(t(date, '%j')).to.equal('060')
})
it('should take count of leap years', function () {
var date = new Date('2000-03-01')
let 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 () {
var date = new Date('2016-01-01T00:00:00.000Z')
let 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 () {
var st = new Date('2016-03-01T03:05:03.000Z')
var nd = new Date('2016-03-02T03:05:03.000Z')
var rd = new Date('2016-03-03T03:05:03.000Z')
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')
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 () {
var date = new Date('2016-01-04T13:15:23.000Z')
let 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 () {
var p = Date.prototype
let p = Date.prototype
p._getHours = p.getHours
p.getHours = p.getUTCHours
@@ -139,7 +139,7 @@ function mockUTC () {
}
function restoreUTC () {
var p = Date.prototype
let p = Date.prototype
p.getHours = p._getHours
p.getDays = p._getDays
p.getTimezoneOffset = p._getTimezoneOffset
+15 -15
View File
@@ -1,10 +1,10 @@
const chai = require('chai')
const sinon = require('sinon')
const expect = chai.expect
const Errors = require('../../src/util/error.js')
chai.use(require('sinon-chai'))
import chai from 'chai'
import sinon from 'sinon'
import Errors from '../../src/util/error.js'
import _ from '../../src/util/underscore.js'
var _ = require('../../src/util/underscore.js')
const expect = chai.expect
chai.use(require('sinon-chai'))
describe('util/underscore', function () {
describe('.isError()', function () {
@@ -12,7 +12,7 @@ describe('util/underscore', function () {
expect(_.isError(new Error())).to.be.true
})
it('should return true for RenderError', function () {
var tpl = {
let tpl = {
token: {
input: 'xx'
}
@@ -53,21 +53,21 @@ describe('util/underscore', function () {
})
describe('.forOwn()', function () {
it('should iterate all properties', function () {
var spy = sinon.spy()
var obj = {
let spy = sinon.spy()
let obj = {
foo: 'bar'
}
_.forOwn(obj, spy)
expect(spy).to.have.been.calledWith('bar', 'foo', obj)
})
it('should default to empty object', function () {
var spy = sinon.spy()
let spy = sinon.spy()
_.forOwn(undefined, spy)
expect(spy).to.have.not.been.called
})
it('should not iterate over properties on prototype', function () {
var spy = sinon.spy()
var obj = Object.create({
let spy = sinon.spy()
let obj = Object.create({
bar: 'foo'
})
obj.foo = 'bar'
@@ -76,7 +76,7 @@ describe('util/underscore', function () {
expect(spy).to.have.been.calledWith('bar', 'foo', obj)
})
it('should break when returned false', function () {
var spy = sinon.stub().returns(false)
let spy = sinon.stub().returns(false)
_.forOwn({
'foo': 'foo',
'bar': 'foo'
@@ -101,11 +101,11 @@ describe('util/underscore', function () {
})
})
it('should assign 2 objects', function () {
var src = {
let src = {
foo: 'foo',
bar: 'bar'
}
var dst = {
let dst = {
foo: 'bar',
kaa: 'kaa'
}
+1 -1
View File
@@ -7,7 +7,7 @@ describe('util/url', function () {
return
}
const JSDOM = require('jsdom').JSDOM
var dom
let dom
beforeEach(function () {
dom = new JSDOM(``, {
url: 'https://example.com/foo/bar/',
+4 -4
View File
@@ -1,6 +1,6 @@
const Liquid = require('..')
const sinon = require('sinon')
const chai = require('chai')
import Liquid from '..'
import sinon from 'sinon'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
@@ -9,7 +9,7 @@ describe('xhr', () => {
return
}
const JSDOM = require('jsdom').JSDOM
var server, engine, dom
let server, engine, dom
beforeEach(() => {
server = sinon.createFakeServer()
server.autoRespond = true