mirror of
https://github.com/harttle/liquidjs.git
synced 2026-10-03 09:05:14 -07:00
chore(TypeScript): refactor objects into classes
fix: `Nil`(null, undefined) now renders as empty string change: `parser.parseValue()` renamed to `parser.parseOutput` change: registered tags/filters become static and shared across different liquid instances
This commit is contained in:
@@ -1,12 +1,16 @@
|
|||||||
{
|
{
|
||||||
"extends": "standard",
|
"extends": "standard",
|
||||||
"env": {
|
"env": {
|
||||||
|
"mocha": true,
|
||||||
"es6": true,
|
"es6": true,
|
||||||
"browser": true,
|
"browser": true,
|
||||||
"node": true
|
"node": true
|
||||||
},
|
},
|
||||||
|
"parser": "@typescript-eslint/parser",
|
||||||
"plugins": [
|
"plugins": [
|
||||||
|
"mocha",
|
||||||
"standard",
|
"standard",
|
||||||
|
"@typescript-eslint",
|
||||||
"promise"
|
"promise"
|
||||||
],
|
],
|
||||||
"rules": {
|
"rules": {
|
||||||
|
|||||||
@@ -212,7 +212,7 @@ Filter arguments will be passed to the registered filter function, for example:
|
|||||||
engine.registerFilter('add', (initial, arg1, arg2) => initial + arg1 + arg2)
|
engine.registerFilter('add', (initial, arg1, arg2) => initial + arg1 + arg2)
|
||||||
```
|
```
|
||||||
|
|
||||||
See existing filter implementations here: <https://github.com/harttle/liquidjs/blob/master/filters.js>
|
See existing filter implementations here: <https://github.com/harttle/liquidjs/tree/master/src/builtin/filters>
|
||||||
|
|
||||||
## Register Tags
|
## Register Tags
|
||||||
|
|
||||||
@@ -232,7 +232,7 @@ engine.registerTag('upper', {
|
|||||||
* `parse`: Read tokens from `remainTokens` until your end token.
|
* `parse`: Read tokens from `remainTokens` until your end token.
|
||||||
* `render`: Combine scope data with your parsed tokens into HTML string.
|
* `render`: Combine scope data with your parsed tokens into HTML string.
|
||||||
|
|
||||||
See existing tag implementations here: <https://github.com/harttle/liquidjs/blob/master/tags/>
|
See existing tag implementations here: <https://github.com/harttle/liquidjs/tree/master/src/builtin/tags>
|
||||||
|
|
||||||
## Plugin API
|
## Plugin API
|
||||||
|
|
||||||
|
|||||||
Generated
+1586
-2184
File diff suppressed because it is too large
Load Diff
+6
-5
@@ -3,13 +3,11 @@
|
|||||||
"version": "7.0.0",
|
"version": "7.0.0",
|
||||||
"description": "Liquid template engine by pure JavaScript: compatible to shopify, easy to extend.",
|
"description": "Liquid template engine by pure JavaScript: compatible to shopify, easy to extend.",
|
||||||
"main": "dist/liquid.common.js",
|
"main": "dist/liquid.common.js",
|
||||||
"module": "src/index.js",
|
|
||||||
"browser": "dist/liquid.js",
|
"browser": "dist/liquid.js",
|
||||||
"types": "src/index.d.ts",
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"lint": "eslint src/ test/ *.js",
|
"lint": "eslint src/ test/ *.js",
|
||||||
"unit": "mocha test/unit",
|
"unit": "mocha -r ts-node/register -r tsconfig-paths/register test/unit/**.ts",
|
||||||
"e2e": "mocha test/e2e",
|
"e2e": "npm run build && mocha -r ts-node/register -r tsconfig-paths/register test/e2e/**/*.ts",
|
||||||
"test": "npm run unit && npm run e2e",
|
"test": "npm run unit && npm run e2e",
|
||||||
"coverage": "nyc --reporter=html npm run unit",
|
"coverage": "nyc --reporter=html npm run unit",
|
||||||
"coveralls": "nyc report --reporter=text-lcov | coveralls",
|
"coveralls": "nyc report --reporter=text-lcov | coveralls",
|
||||||
@@ -42,6 +40,9 @@
|
|||||||
"@semantic-release/git": "^7.0.8",
|
"@semantic-release/git": "^7.0.8",
|
||||||
"@semantic-release/npm": "^5.1.4",
|
"@semantic-release/npm": "^5.1.4",
|
||||||
"@semantic-release/release-notes-generator": "^7.1.4",
|
"@semantic-release/release-notes-generator": "^7.1.4",
|
||||||
|
"@types/jsdom": "^12.2.2",
|
||||||
|
"@types/mocha": "^5.2.6",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^1.3.0",
|
||||||
"chai": "^4.2.0",
|
"chai": "^4.2.0",
|
||||||
"chai-as-promised": "^7.1.1",
|
"chai-as-promised": "^7.1.1",
|
||||||
"coveralls": "^3.0.2",
|
"coveralls": "^3.0.2",
|
||||||
@@ -60,7 +61,6 @@
|
|||||||
"nyc": "^13.1.0",
|
"nyc": "^13.1.0",
|
||||||
"regenerator-runtime": "^0.12.1",
|
"regenerator-runtime": "^0.12.1",
|
||||||
"rollup": "^1.1.2",
|
"rollup": "^1.1.2",
|
||||||
"rollup-plugin-alias": "^1.5.1",
|
|
||||||
"rollup-plugin-shim": "^1.0.0",
|
"rollup-plugin-shim": "^1.0.0",
|
||||||
"rollup-plugin-typescript2": "^0.19.2",
|
"rollup-plugin-typescript2": "^0.19.2",
|
||||||
"rollup-plugin-uglify": "^6.0.2",
|
"rollup-plugin-uglify": "^6.0.2",
|
||||||
@@ -69,6 +69,7 @@
|
|||||||
"sinon-chai": "^3.3.0",
|
"sinon-chai": "^3.3.0",
|
||||||
"supertest": "^3.4.2",
|
"supertest": "^3.4.2",
|
||||||
"ts-node": "^8.0.2",
|
"ts-node": "^8.0.2",
|
||||||
|
"tsconfig-paths": "^3.8.0",
|
||||||
"typescript": "^3.3.3"
|
"typescript": "^3.3.3"
|
||||||
},
|
},
|
||||||
"release": {
|
"release": {
|
||||||
|
|||||||
+34
-11
@@ -1,5 +1,4 @@
|
|||||||
import shim from 'rollup-plugin-shim'
|
import shim from 'rollup-plugin-shim'
|
||||||
import alias from 'rollup-plugin-alias'
|
|
||||||
import { uglify } from 'rollup-plugin-uglify'
|
import { uglify } from 'rollup-plugin-uglify'
|
||||||
import pkg from './package.json'
|
import pkg from './package.json'
|
||||||
import typescript from 'rollup-plugin-typescript2'
|
import typescript from 'rollup-plugin-typescript2'
|
||||||
@@ -15,11 +14,7 @@ const banner = `/*
|
|||||||
const treeshake = {
|
const treeshake = {
|
||||||
propertyReadSideEffects: false
|
propertyReadSideEffects: false
|
||||||
}
|
}
|
||||||
const input = 'src/index.ts'
|
const input = 'src/liquid.ts'
|
||||||
const tsOptions = {
|
|
||||||
include: [ '*.ts', '**/*.ts', '*.js', '**/*.js' ],
|
|
||||||
tsconfigOverride: { compilerOptions: { module: 'ES2015' } }
|
|
||||||
}
|
|
||||||
|
|
||||||
export default [{
|
export default [{
|
||||||
output: [{
|
output: [{
|
||||||
@@ -30,7 +25,17 @@ export default [{
|
|||||||
banner
|
banner
|
||||||
}],
|
}],
|
||||||
external: ['path', 'fs'],
|
external: ['path', 'fs'],
|
||||||
plugins: [typescript(tsOptions)],
|
plugins: [typescript({
|
||||||
|
include: [ '*.ts', '**/*.ts', '*.js', '**/*.js' ],
|
||||||
|
tsconfigOverride: { compilerOptions: {
|
||||||
|
module: 'ES2015',
|
||||||
|
baseUrl: '.',
|
||||||
|
paths: {
|
||||||
|
'template': ['src/parser/template'],
|
||||||
|
'src/*': ['src/*']
|
||||||
|
}
|
||||||
|
} }
|
||||||
|
})],
|
||||||
treeshake,
|
treeshake,
|
||||||
input
|
input
|
||||||
}, {
|
}, {
|
||||||
@@ -43,8 +48,17 @@ export default [{
|
|||||||
}],
|
}],
|
||||||
plugins: [
|
plugins: [
|
||||||
shim(fake),
|
shim(fake),
|
||||||
alias({ './template': './template-browser' }),
|
typescript({
|
||||||
typescript(tsOptions)
|
include: [ '*.ts', '**/*.ts', '*.js', '**/*.js' ],
|
||||||
|
tsconfigOverride: { compilerOptions: {
|
||||||
|
module: 'ES2015',
|
||||||
|
baseUrl: '.',
|
||||||
|
paths: {
|
||||||
|
'template': ['src/parser/template-browser'],
|
||||||
|
'src/*': ['src/*']
|
||||||
|
}
|
||||||
|
} }
|
||||||
|
})
|
||||||
],
|
],
|
||||||
treeshake,
|
treeshake,
|
||||||
input
|
input
|
||||||
@@ -57,8 +71,17 @@ export default [{
|
|||||||
}],
|
}],
|
||||||
plugins: [
|
plugins: [
|
||||||
shim(fake),
|
shim(fake),
|
||||||
alias({ './template': './template-browser' }),
|
typescript({
|
||||||
typescript(tsOptions),
|
include: [ '*.ts', '**/*.ts', '*.js', '**/*.js' ],
|
||||||
|
tsconfigOverride: { compilerOptions: {
|
||||||
|
module: 'ES2015',
|
||||||
|
baseUrl: '.',
|
||||||
|
paths: {
|
||||||
|
'template': ['src/parser/template-browser'],
|
||||||
|
'src/*': ['src/*']
|
||||||
|
}
|
||||||
|
} }
|
||||||
|
}),
|
||||||
uglify()
|
uglify()
|
||||||
],
|
],
|
||||||
treeshake,
|
treeshake,
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { last } from 'src/util/underscore'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
'join': (v, arg) => v.join(arg === undefined ? ' ' : arg),
|
||||||
|
'last': v => last(v),
|
||||||
|
'first': v => v[0],
|
||||||
|
'map': (arr, arg) => arr.map(v => v[arg]),
|
||||||
|
'reverse': v => v.reverse(),
|
||||||
|
'sort': (v, arg) => v.sort(arg),
|
||||||
|
'size': v => v.length,
|
||||||
|
'slice': (v, begin, length) => {
|
||||||
|
if (length === undefined) length = 1
|
||||||
|
return v.slice(begin, begin + length)
|
||||||
|
},
|
||||||
|
'uniq': function (arr) {
|
||||||
|
const u = {}
|
||||||
|
return (arr || []).filter(val => {
|
||||||
|
if (u.hasOwnProperty(val)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
u[val] = true
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import strftime from 'src/util/strftime'
|
||||||
|
import { isString } from 'src/util/underscore'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
'date': (v, arg) => {
|
||||||
|
let date = v
|
||||||
|
if (v === 'now') {
|
||||||
|
date = new Date()
|
||||||
|
} else if (isString(v)) {
|
||||||
|
date = new Date(v)
|
||||||
|
}
|
||||||
|
return isValidDate(date) ? strftime(date, arg) : v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidDate (date) {
|
||||||
|
return date instanceof Date && !isNaN(date.getTime())
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
const escapeMap = {
|
||||||
|
'&': '&',
|
||||||
|
'<': '<',
|
||||||
|
'>': '>',
|
||||||
|
'"': '"',
|
||||||
|
"'": '''
|
||||||
|
}
|
||||||
|
const unescapeMap = {
|
||||||
|
'&': '&',
|
||||||
|
'<': '<',
|
||||||
|
'>': '>',
|
||||||
|
'"': '"',
|
||||||
|
''': "'"
|
||||||
|
}
|
||||||
|
|
||||||
|
function escape (str) {
|
||||||
|
return String(str).replace(/&|<|>|"|'/g, m => escapeMap[m])
|
||||||
|
}
|
||||||
|
|
||||||
|
function unescape (str) {
|
||||||
|
return String(str).replace(/&(amp|lt|gt|#34|#39);/g, m => unescapeMap[m])
|
||||||
|
}
|
||||||
|
|
||||||
|
export default {
|
||||||
|
'escape': escape,
|
||||||
|
'escape_once': str => escape(unescape(str)),
|
||||||
|
'newline_to_br': v => v.replace(/\n/g, '<br />'),
|
||||||
|
'strip_html': v => String(v).replace(/<script.*?<\/script>|<!--.*?-->|<style.*?<\/style>|<.*?>/g, ''),
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { assign } from 'src/util/underscore'
|
||||||
|
import html from './html'
|
||||||
|
import str from './string'
|
||||||
|
import math from './math'
|
||||||
|
import url from './url'
|
||||||
|
import array from './array'
|
||||||
|
import date from './date'
|
||||||
|
import obj from './object'
|
||||||
|
|
||||||
|
const filters = assign({}, html, str, math, url, date, obj, array)
|
||||||
|
|
||||||
|
export default filters
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
export default {
|
||||||
|
'abs': v => Math.abs(v),
|
||||||
|
'ceil': v => Math.ceil(v),
|
||||||
|
'divided_by': (v, arg) => v / arg,
|
||||||
|
'floor': v => Math.floor(v),
|
||||||
|
'minus': bindFixed((v, arg) => v - arg),
|
||||||
|
'modulo': bindFixed((v, arg) => v % arg),
|
||||||
|
'round': (v, arg) => {
|
||||||
|
const amp = Math.pow(10, arg || 0)
|
||||||
|
return Math.round(v * amp) / amp
|
||||||
|
},
|
||||||
|
'plus': bindFixed((v, arg) => Number(v) + Number(arg)),
|
||||||
|
'times': (v, arg) => v * arg,
|
||||||
|
}
|
||||||
|
|
||||||
|
function getFixed (v) {
|
||||||
|
const p = String(v).split('.')
|
||||||
|
return (p.length > 1) ? p[1].length : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindFixed (cb) {
|
||||||
|
return (l, r) => {
|
||||||
|
const f = Math.max(getFixed(l), getFixed(r))
|
||||||
|
return cb(l, r).toFixed(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { isTruthy } from 'src/render/syntax'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
'default': (v, arg) => isTruthy(v) ? v : arg
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
export default {
|
||||||
|
'append': (v, arg) => v + arg,
|
||||||
|
'prepend': (v, arg) => arg + v,
|
||||||
|
'capitalize': str => String(str).charAt(0).toUpperCase() + str.slice(1),
|
||||||
|
'concat': (v, arg) => Array.prototype.concat.call(v, arg),
|
||||||
|
'lstrip': v => String(v).replace(/^\s+/, ''),
|
||||||
|
'downcase': v => v.toLowerCase(),
|
||||||
|
'upcase': str => String(str).toUpperCase(),
|
||||||
|
'remove': (v, arg) => v.split(arg).join(''),
|
||||||
|
'remove_first': (v, l) => v.replace(l, ''),
|
||||||
|
'replace': (v, pattern, replacement) =>
|
||||||
|
String(v).split(pattern).join(replacement),
|
||||||
|
'replace_first': (v, arg1, arg2) => String(v).replace(arg1, arg2),
|
||||||
|
'rstrip': str => String(str).replace(/\s+$/, ''),
|
||||||
|
'split': (v, arg) => String(v).split(arg),
|
||||||
|
'strip': (v) => String(v).trim(),
|
||||||
|
'strip_newlines': v => String(v).replace(/\n/g, ''),
|
||||||
|
'truncate': (v, l, o) => {
|
||||||
|
v = String(v)
|
||||||
|
o = (o === undefined) ? '...' : o
|
||||||
|
l = l || 16
|
||||||
|
if (v.length <= l) return v
|
||||||
|
return v.substr(0, l - o.length) + o
|
||||||
|
},
|
||||||
|
'truncatewords': (v, l, o) => {
|
||||||
|
if (o === undefined) o = '...'
|
||||||
|
const arr = v.split(' ')
|
||||||
|
let ret = arr.slice(0, l).join(' ')
|
||||||
|
if (arr.length > l) ret += o
|
||||||
|
return ret
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export default {
|
||||||
|
'url_decode': x => x.split('+').map(decodeURIComponent).join(' '),
|
||||||
|
'url_encode': x => x.split(' ').map(encodeURIComponent).join('+')
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import assert from 'src/util/assert'
|
||||||
|
import { identifier } from 'src/parser/lexical'
|
||||||
|
import { AssignScope } from 'src/scope/scopes'
|
||||||
|
|
||||||
|
const re = new RegExp(`(${identifier.source})\\s*=([^]*)`)
|
||||||
|
|
||||||
|
export default {
|
||||||
|
parse: function (token) {
|
||||||
|
const match = token.args.match(re)
|
||||||
|
assert(match, `illegal token ${token.raw}`)
|
||||||
|
this.key = match[1]
|
||||||
|
this.value = match[2]
|
||||||
|
},
|
||||||
|
render: function (scope) {
|
||||||
|
const ctx = new AssignScope()
|
||||||
|
ctx[this.key] = this.liquid.evalValue(this.value, scope)
|
||||||
|
scope.push(ctx)
|
||||||
|
return Promise.resolve('')
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import BlockMode from 'src/scope/block-mode'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
parse: function (token, remainTokens) {
|
||||||
|
const match = /\w+/.exec(token.args)
|
||||||
|
this.block = match ? match[0] : ''
|
||||||
|
|
||||||
|
this.tpls = []
|
||||||
|
const stream = this.liquid.parser.parseStream(remainTokens)
|
||||||
|
.on('tag:endblock', () => stream.stop())
|
||||||
|
.on('template', tpl => this.tpls.push(tpl))
|
||||||
|
.on('end', () => {
|
||||||
|
throw new Error(`tag ${token.raw} not closed`)
|
||||||
|
})
|
||||||
|
stream.start()
|
||||||
|
},
|
||||||
|
render: async function (scope) {
|
||||||
|
const childDefined = scope.blocks[this.block]
|
||||||
|
const html = childDefined !== undefined
|
||||||
|
? childDefined
|
||||||
|
: await this.liquid.renderer.renderTemplates(this.tpls, scope)
|
||||||
|
|
||||||
|
if (scope.blockMode === BlockMode.STORE) {
|
||||||
|
scope.blocks[this.block] = html
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
return html
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { RenderBreakError } from 'src/util/error'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
render: async function (scope) {
|
||||||
|
throw new RenderBreakError('break')
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import assert from 'src/util/assert'
|
||||||
|
import { identifier } from 'src/parser/lexical'
|
||||||
|
import { CaptureScope } from 'src/scope/scopes'
|
||||||
|
|
||||||
|
const re = new RegExp(`(${identifier.source})`)
|
||||||
|
|
||||||
|
export default {
|
||||||
|
parse: function (tagToken, remainTokens) {
|
||||||
|
const match = tagToken.args.match(re)
|
||||||
|
assert(match, `${tagToken.args} not valid identifier`)
|
||||||
|
|
||||||
|
this.variable = match[1]
|
||||||
|
this.templates = []
|
||||||
|
|
||||||
|
const stream = this.liquid.parser.parseStream(remainTokens)
|
||||||
|
stream.on('tag:endcapture', token => stream.stop())
|
||||||
|
.on('template', tpl => this.templates.push(tpl))
|
||||||
|
.on('end', x => {
|
||||||
|
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||||
|
})
|
||||||
|
stream.start()
|
||||||
|
},
|
||||||
|
render: async function (scope, hash) {
|
||||||
|
const html = await this.liquid.renderer.renderTemplates(this.templates, scope)
|
||||||
|
const ctx = new CaptureScope()
|
||||||
|
ctx[this.variable] = html
|
||||||
|
scope.push(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { evalExp } from 'src/render/syntax'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
parse: function (tagToken, remainTokens) {
|
||||||
|
this.cond = tagToken.args
|
||||||
|
this.cases = []
|
||||||
|
this.elseTemplates = []
|
||||||
|
|
||||||
|
let p = []
|
||||||
|
const stream = this.liquid.parser.parseStream(remainTokens)
|
||||||
|
.on('tag:when', token => {
|
||||||
|
this.cases.push({
|
||||||
|
val: token.args,
|
||||||
|
templates: p = []
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.on('tag:else', () => (p = this.elseTemplates))
|
||||||
|
.on('tag:endcase', token => stream.stop())
|
||||||
|
.on('template', tpl => p.push(tpl))
|
||||||
|
.on('end', x => {
|
||||||
|
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||||
|
})
|
||||||
|
|
||||||
|
stream.start()
|
||||||
|
},
|
||||||
|
|
||||||
|
render: function (scope, hash) {
|
||||||
|
for (let i = 0; i < this.cases.length; i++) {
|
||||||
|
const branch = this.cases[i]
|
||||||
|
const val = evalExp(branch.val, scope)
|
||||||
|
const cond = evalExp(this.cond, scope)
|
||||||
|
if (val === cond) {
|
||||||
|
return this.liquid.renderer.renderTemplates(branch.templates, scope)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
export default {
|
||||||
|
parse: function (tagToken, remainTokens) {
|
||||||
|
const stream = this.liquid.parser.parseStream(remainTokens)
|
||||||
|
stream
|
||||||
|
.on('token', token => {
|
||||||
|
if (token.name === 'endcomment') stream.stop()
|
||||||
|
})
|
||||||
|
.on('end', x => {
|
||||||
|
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||||
|
})
|
||||||
|
stream.start()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { RenderBreakError } from 'src/util/error'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
render: async function (scope) {
|
||||||
|
throw new RenderBreakError('continue')
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import assert from 'src/util/assert'
|
||||||
|
import { value as rValue } from 'src/parser/lexical'
|
||||||
|
import { evalValue } from 'src/render/syntax'
|
||||||
|
|
||||||
|
const groupRE = new RegExp(`^(?:(${rValue.source})\\s*:\\s*)?(.*)$`)
|
||||||
|
const candidatesRE = new RegExp(rValue.source, 'g')
|
||||||
|
|
||||||
|
export default {
|
||||||
|
parse: function (tagToken, remainTokens) {
|
||||||
|
let match = groupRE.exec(tagToken.args)
|
||||||
|
assert(match, `illegal tag: ${tagToken.raw}`)
|
||||||
|
|
||||||
|
this.group = match[1] || ''
|
||||||
|
const candidates = match[2]
|
||||||
|
|
||||||
|
this.candidates = []
|
||||||
|
|
||||||
|
while ((match = candidatesRE.exec(candidates))) {
|
||||||
|
this.candidates.push(match[0])
|
||||||
|
}
|
||||||
|
assert(this.candidates.length, `empty candidates: ${tagToken.raw}`)
|
||||||
|
},
|
||||||
|
|
||||||
|
render: function (scope, hash) {
|
||||||
|
const group = evalValue(this.group, scope)
|
||||||
|
const fingerprint = `cycle:${group}:` + this.candidates.join(',')
|
||||||
|
|
||||||
|
const groups = scope.opts.groups = scope.opts.groups || {}
|
||||||
|
let idx = groups[fingerprint]
|
||||||
|
|
||||||
|
if (idx === undefined) {
|
||||||
|
idx = groups[fingerprint] = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
const candidate = this.candidates[idx]
|
||||||
|
idx = (idx + 1) % this.candidates.length
|
||||||
|
groups[fingerprint] = idx
|
||||||
|
|
||||||
|
return evalValue(candidate, scope)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import assert from 'src/util/assert'
|
||||||
|
import { identifier } from 'src/parser/lexical'
|
||||||
|
import { CaptureScope, AssignScope, DecrementScope } from 'src/scope/scopes'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
parse: function (token) {
|
||||||
|
const match = token.args.match(identifier)
|
||||||
|
assert(match, `illegal identifier ${token.args}`)
|
||||||
|
this.variable = match[0]
|
||||||
|
},
|
||||||
|
render: function (scope, hash) {
|
||||||
|
let context = scope.findContextFor(
|
||||||
|
this.variable,
|
||||||
|
ctx => {
|
||||||
|
return !(ctx instanceof CaptureScope) && !(ctx instanceof AssignScope)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if (!context) {
|
||||||
|
context = new DecrementScope()
|
||||||
|
scope.unshift(context)
|
||||||
|
}
|
||||||
|
if (typeof context[this.variable] !== 'number') {
|
||||||
|
context[this.variable] = 0
|
||||||
|
}
|
||||||
|
return --context[this.variable]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import { mapSeries } from 'src/util/promise'
|
||||||
|
import { isString, isObject, isArray } from 'src/util/underscore'
|
||||||
|
import { evalExp } from 'src/render/syntax'
|
||||||
|
import assert from 'src/util/assert'
|
||||||
|
import { identifier, value, hash } from 'src/parser/lexical'
|
||||||
|
import { RenderBreakError } from 'src/util/error'
|
||||||
|
|
||||||
|
const re = new RegExp(`^(${identifier.source})\\s+in\\s+` +
|
||||||
|
`(${value.source})` +
|
||||||
|
`(?:\\s+${hash.source})*` +
|
||||||
|
`(?:\\s+(reversed))?` +
|
||||||
|
`(?:\\s+${hash.source})*$`)
|
||||||
|
|
||||||
|
function parse (tagToken, remainTokens) {
|
||||||
|
const match = re.exec(tagToken.args)
|
||||||
|
assert(match, `illegal tag: ${tagToken.raw}`)
|
||||||
|
this.variable = match[1]
|
||||||
|
this.collection = match[2]
|
||||||
|
this.reversed = !!match[3]
|
||||||
|
|
||||||
|
this.templates = []
|
||||||
|
this.elseTemplates = []
|
||||||
|
|
||||||
|
let p
|
||||||
|
const stream = this.liquid.parser.parseStream(remainTokens)
|
||||||
|
.on('start', () => (p = this.templates))
|
||||||
|
.on('tag:else', () => (p = this.elseTemplates))
|
||||||
|
.on('tag:endfor', () => stream.stop())
|
||||||
|
.on('template', tpl => p.push(tpl))
|
||||||
|
.on('end', () => {
|
||||||
|
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||||
|
})
|
||||||
|
|
||||||
|
stream.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function render (scope, hash) {
|
||||||
|
let collection = evalExp(this.collection, scope)
|
||||||
|
|
||||||
|
if (!isArray(collection)) {
|
||||||
|
if (isString(collection) && collection.length > 0) {
|
||||||
|
collection = [collection]
|
||||||
|
} else if (isObject(collection)) {
|
||||||
|
collection = Object.keys(collection).map((key) => [key, collection[key]])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!isArray(collection) || !collection.length) {
|
||||||
|
return this.liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
const offset = hash.offset || 0
|
||||||
|
const limit = (hash.limit === undefined) ? collection.length : hash.limit
|
||||||
|
|
||||||
|
collection = collection.slice(offset, offset + limit)
|
||||||
|
if (this.reversed) collection.reverse()
|
||||||
|
|
||||||
|
const contexts = collection.map((item, i) => {
|
||||||
|
const ctx = {}
|
||||||
|
ctx[this.variable] = item
|
||||||
|
ctx['forloop'] = {
|
||||||
|
first: i === 0,
|
||||||
|
index: i + 1,
|
||||||
|
index0: i,
|
||||||
|
last: i === collection.length - 1,
|
||||||
|
length: collection.length,
|
||||||
|
rindex: collection.length - i,
|
||||||
|
rindex0: collection.length - i - 1
|
||||||
|
}
|
||||||
|
return ctx
|
||||||
|
})
|
||||||
|
|
||||||
|
let html = ''
|
||||||
|
let finished = false
|
||||||
|
await mapSeries(contexts, async context => {
|
||||||
|
if (finished) return
|
||||||
|
|
||||||
|
scope.push(context)
|
||||||
|
try {
|
||||||
|
html += await this.liquid.renderer.renderTemplates(this.templates, scope)
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof RenderBreakError) {
|
||||||
|
html += e.resolvedHTML
|
||||||
|
if (e.message === 'break') {
|
||||||
|
finished = true
|
||||||
|
}
|
||||||
|
} else throw e
|
||||||
|
}
|
||||||
|
scope.pop(context)
|
||||||
|
})
|
||||||
|
return html
|
||||||
|
}
|
||||||
|
|
||||||
|
export default { parse, render }
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { evalExp, isTruthy } from 'src/render/syntax'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
parse: function (tagToken, remainTokens) {
|
||||||
|
this.branches = []
|
||||||
|
this.elseTemplates = []
|
||||||
|
|
||||||
|
let p
|
||||||
|
const stream = this.liquid.parser.parseStream(remainTokens)
|
||||||
|
.on('start', () => this.branches.push({
|
||||||
|
cond: tagToken.args,
|
||||||
|
templates: (p = [])
|
||||||
|
}))
|
||||||
|
.on('tag:elsif', token => {
|
||||||
|
this.branches.push({
|
||||||
|
cond: token.args,
|
||||||
|
templates: p = []
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.on('tag:else', () => (p = this.elseTemplates))
|
||||||
|
.on('tag:endif', token => stream.stop())
|
||||||
|
.on('template', tpl => p.push(tpl))
|
||||||
|
.on('end', x => {
|
||||||
|
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||||
|
})
|
||||||
|
|
||||||
|
stream.start()
|
||||||
|
},
|
||||||
|
|
||||||
|
render: function (scope, hash) {
|
||||||
|
for (const branch of this.branches) {
|
||||||
|
const cond = evalExp(branch.cond, scope)
|
||||||
|
if (isTruthy(cond)) {
|
||||||
|
return this.liquid.renderer.renderTemplates(branch.templates, scope)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import assert from 'src/util/assert'
|
||||||
|
import { value, quotedLine } from 'src/parser/lexical'
|
||||||
|
import { evalValue } from 'src/render/syntax'
|
||||||
|
import BlockMode from 'src/scope/block-mode'
|
||||||
|
|
||||||
|
const staticFileRE = /[^\s,]+/
|
||||||
|
const withRE = new RegExp(`with\\s+(${value.source})`)
|
||||||
|
|
||||||
|
export default {
|
||||||
|
parse: function (token) {
|
||||||
|
let match = staticFileRE.exec(token.args)
|
||||||
|
if (match) {
|
||||||
|
this.staticValue = match[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
match = value.exec(token.args)
|
||||||
|
if (match) {
|
||||||
|
this.value = match[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
match = withRE.exec(token.args)
|
||||||
|
if (match) {
|
||||||
|
this.with = match[1]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
render: async function (scope, hash) {
|
||||||
|
let filepath
|
||||||
|
if (scope.opts.dynamicPartials) {
|
||||||
|
if (quotedLine.exec(this.value)) {
|
||||||
|
const template = this.value.slice(1, -1)
|
||||||
|
filepath = await this.liquid.parseAndRender(template, scope.getAll(), scope.opts)
|
||||||
|
} else {
|
||||||
|
filepath = evalValue(this.value, scope)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
filepath = this.staticValue
|
||||||
|
}
|
||||||
|
assert(filepath, `cannot include with empty filename`)
|
||||||
|
|
||||||
|
const originBlocks = scope.blocks
|
||||||
|
const originBlockMode = scope.blockMode
|
||||||
|
|
||||||
|
scope.blocks = {}
|
||||||
|
scope.blockMode = BlockMode.OUTPUT
|
||||||
|
if (this.with) {
|
||||||
|
hash[filepath] = evalValue(this.with, scope)
|
||||||
|
}
|
||||||
|
const templates = await this.liquid.getTemplate(filepath, scope.opts.root)
|
||||||
|
scope.push(hash)
|
||||||
|
const html = await this.liquid.renderer.renderTemplates(templates, scope)
|
||||||
|
scope.pop(hash)
|
||||||
|
scope.blocks = originBlocks
|
||||||
|
scope.blockMode = originBlockMode
|
||||||
|
return html
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import assert from 'src/util/assert'
|
||||||
|
import { identifier } from 'src/parser/lexical'
|
||||||
|
import { CaptureScope, AssignScope, IncrementScope } from 'src/scope/scopes'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
parse: function (token) {
|
||||||
|
const match = token.args.match(identifier)
|
||||||
|
assert(match, `illegal identifier ${token.args}`)
|
||||||
|
this.variable = match[0]
|
||||||
|
},
|
||||||
|
render: function (scope, hash) {
|
||||||
|
let context = scope.findContextFor(
|
||||||
|
this.variable,
|
||||||
|
ctx => {
|
||||||
|
return !(ctx instanceof CaptureScope) && !(ctx instanceof AssignScope)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if (!context) {
|
||||||
|
context = new IncrementScope()
|
||||||
|
scope.unshift(context)
|
||||||
|
}
|
||||||
|
if (typeof context[this.variable] !== 'number') {
|
||||||
|
context[this.variable] = 0
|
||||||
|
}
|
||||||
|
const val = context[this.variable]
|
||||||
|
context[this.variable]++
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import assign from './assign'
|
||||||
|
import For from './for'
|
||||||
|
import capture from './capture'
|
||||||
|
import Case from './case'
|
||||||
|
import comment from './comment'
|
||||||
|
import include from './include'
|
||||||
|
import decrement from './decrement'
|
||||||
|
import cycle from './cycle'
|
||||||
|
import If from './if'
|
||||||
|
import increment from './increment'
|
||||||
|
import layout from './layout'
|
||||||
|
import block from './block'
|
||||||
|
import raw from './raw'
|
||||||
|
import tablerow from './tablerow'
|
||||||
|
import unless from './unless'
|
||||||
|
import Break from './break'
|
||||||
|
import Continue from './continue'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
assign, 'for': For, capture, 'case': Case, comment, include, decrement, increment, cycle, 'if': If, layout, block, raw, tablerow, unless, 'break': Break, 'continue': Continue
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import assert from 'src/util/assert'
|
||||||
|
import { value as rValue } from 'src/parser/lexical'
|
||||||
|
import { evalValue } from 'src/render/syntax'
|
||||||
|
import BlockMode from 'src/scope/block-mode'
|
||||||
|
|
||||||
|
const staticFileRE = /\S+/
|
||||||
|
|
||||||
|
export default {
|
||||||
|
parse: function (token, remainTokens) {
|
||||||
|
let match = staticFileRE.exec(token.args)
|
||||||
|
if (match) {
|
||||||
|
this.staticLayout = match[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
match = rValue.exec(token.args)
|
||||||
|
if (match) {
|
||||||
|
this.layout = match[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
this.tpls = this.liquid.parser.parse(remainTokens)
|
||||||
|
},
|
||||||
|
render: async function (scope, hash) {
|
||||||
|
const layout = scope.opts.dynamicPartials
|
||||||
|
? evalValue(this.layout, scope)
|
||||||
|
: this.staticLayout
|
||||||
|
assert(layout, `cannot apply layout with empty filename`)
|
||||||
|
|
||||||
|
// render the remaining tokens immediately
|
||||||
|
scope.blockMode = BlockMode.STORE
|
||||||
|
const html = await this.liquid.renderer.renderTemplates(this.tpls, scope)
|
||||||
|
if (scope.blocks[''] === undefined) {
|
||||||
|
scope.blocks[''] = html
|
||||||
|
}
|
||||||
|
const templates = await this.liquid.getTemplate(layout, scope.opts.root)
|
||||||
|
scope.push(hash)
|
||||||
|
scope.blockMode = BlockMode.OUTPUT
|
||||||
|
const partial = await this.liquid.renderer.renderTemplates(templates, scope)
|
||||||
|
scope.pop(hash)
|
||||||
|
return partial
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
export default {
|
||||||
|
parse: function (tagToken, remainTokens) {
|
||||||
|
this.tokens = []
|
||||||
|
|
||||||
|
const stream = this.liquid.parser.parseStream(remainTokens)
|
||||||
|
stream
|
||||||
|
.on('token', token => {
|
||||||
|
if (token.name === 'endraw') stream.stop()
|
||||||
|
else this.tokens.push(token)
|
||||||
|
})
|
||||||
|
.on('end', () => {
|
||||||
|
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||||
|
})
|
||||||
|
stream.start()
|
||||||
|
},
|
||||||
|
render: function (scope, hash) {
|
||||||
|
return this.tokens.map(token => token.raw).join('')
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { mapSeries } from 'src/util/promise'
|
||||||
|
import assert from 'src/util/assert'
|
||||||
|
import { evalExp } from 'src/render/syntax'
|
||||||
|
import { identifier, value, hash } from 'src/parser/lexical'
|
||||||
|
|
||||||
|
const re = new RegExp(`^(${identifier.source})\\s+in\\s+` +
|
||||||
|
`(${value.source})` +
|
||||||
|
`(?:\\s+${hash.source})*$`)
|
||||||
|
|
||||||
|
export default {
|
||||||
|
parse: function (tagToken, remainTokens) {
|
||||||
|
const match = re.exec(tagToken.args)
|
||||||
|
assert(match, `illegal tag: ${tagToken.raw}`)
|
||||||
|
|
||||||
|
this.variable = match[1]
|
||||||
|
this.collection = match[2]
|
||||||
|
this.templates = []
|
||||||
|
|
||||||
|
let p
|
||||||
|
const stream = this.liquid.parser.parseStream(remainTokens)
|
||||||
|
.on('start', () => (p = this.templates))
|
||||||
|
.on('tag:endtablerow', token => stream.stop())
|
||||||
|
.on('template', tpl => p.push(tpl))
|
||||||
|
.on('end', () => {
|
||||||
|
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||||
|
})
|
||||||
|
|
||||||
|
stream.start()
|
||||||
|
},
|
||||||
|
|
||||||
|
render: async function (scope, hash) {
|
||||||
|
let collection = evalExp(this.collection, scope) || []
|
||||||
|
const offset = hash.offset || 0
|
||||||
|
const limit = (hash.limit === undefined) ? collection.length : hash.limit
|
||||||
|
|
||||||
|
collection = collection.slice(offset, offset + limit)
|
||||||
|
const cols = hash.cols || collection.length
|
||||||
|
const contexts = collection.map((item, i) => {
|
||||||
|
const ctx = {}
|
||||||
|
ctx[this.variable] = item
|
||||||
|
return ctx
|
||||||
|
})
|
||||||
|
|
||||||
|
let row
|
||||||
|
let html = ''
|
||||||
|
await mapSeries(contexts, async (context, idx) => {
|
||||||
|
row = Math.floor(idx / cols) + 1
|
||||||
|
const col = (idx % cols) + 1
|
||||||
|
if (col === 1) {
|
||||||
|
if (row !== 1) {
|
||||||
|
html += '</tr>'
|
||||||
|
}
|
||||||
|
html += `<tr class="row${row}">`
|
||||||
|
}
|
||||||
|
|
||||||
|
html += `<td class="col${col}">`
|
||||||
|
scope.push(context)
|
||||||
|
html += await this.liquid.renderer.renderTemplates(this.templates, scope)
|
||||||
|
html += '</td>'
|
||||||
|
scope.pop(context)
|
||||||
|
return html
|
||||||
|
})
|
||||||
|
if (row > 0) {
|
||||||
|
html += '</tr>'
|
||||||
|
}
|
||||||
|
return html
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { evalExp, isFalsy } from 'src/render/syntax'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
parse: function (tagToken, remainTokens) {
|
||||||
|
this.templates = []
|
||||||
|
this.elseTemplates = []
|
||||||
|
let p
|
||||||
|
const stream = this.liquid.parser.parseStream(remainTokens)
|
||||||
|
.on('start', x => {
|
||||||
|
p = this.templates
|
||||||
|
this.cond = tagToken.args
|
||||||
|
})
|
||||||
|
.on('tag:else', () => (p = this.elseTemplates))
|
||||||
|
.on('tag:endunless', token => stream.stop())
|
||||||
|
.on('template', tpl => p.push(tpl))
|
||||||
|
.on('end', x => {
|
||||||
|
throw new Error(`tag ${tagToken.raw} not closed`)
|
||||||
|
})
|
||||||
|
|
||||||
|
stream.start()
|
||||||
|
},
|
||||||
|
|
||||||
|
render: function (scope, hash) {
|
||||||
|
const cond = evalExp(this.cond, scope)
|
||||||
|
return isFalsy(cond)
|
||||||
|
? this.liquid.renderer.renderTemplates(this.templates, scope)
|
||||||
|
: this.liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
import * as lexical from './lexical'
|
|
||||||
import { evalValue } from './syntax'
|
|
||||||
import assert from './util/assert'
|
|
||||||
import { assign, create } from './util/underscore'
|
|
||||||
|
|
||||||
const valueRE = new RegExp(`${lexical.value.source}`, 'g')
|
|
||||||
|
|
||||||
export default function (options) {
|
|
||||||
options = assign({}, options)
|
|
||||||
let filters = {}
|
|
||||||
|
|
||||||
const _filterInstance = {
|
|
||||||
render: function (output, scope) {
|
|
||||||
const args = this.args.map(arg => evalValue(arg, scope))
|
|
||||||
args.unshift(output)
|
|
||||||
return this.filter.apply(null, args)
|
|
||||||
},
|
|
||||||
parse: function (str) {
|
|
||||||
let match = lexical.filterLine.exec(str)
|
|
||||||
assert(match, 'illegal filter: ' + str)
|
|
||||||
|
|
||||||
const name = match[1]
|
|
||||||
const argList = match[2] || ''
|
|
||||||
const filter = filters[name]
|
|
||||||
if (typeof filter !== 'function') {
|
|
||||||
if (options.strict_filters) {
|
|
||||||
throw new TypeError(`undefined filter: ${name}`)
|
|
||||||
}
|
|
||||||
this.name = name
|
|
||||||
this.filter = x => x
|
|
||||||
this.args = []
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
const args = []
|
|
||||||
while ((match = valueRE.exec(argList.trim()))) {
|
|
||||||
const v = match[0]
|
|
||||||
const re = new RegExp(`${v}\\s*:`, 'g')
|
|
||||||
const keyMatch = re.exec(match.input)
|
|
||||||
const currentMatchIsKey = keyMatch && keyMatch.index === match.index
|
|
||||||
currentMatchIsKey ? args.push(`'${v}'`) : args.push(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
this.name = name
|
|
||||||
this.filter = filter
|
|
||||||
this.args = args
|
|
||||||
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function construct (str) {
|
|
||||||
const instance = create(_filterInstance)
|
|
||||||
return instance.parse(str)
|
|
||||||
}
|
|
||||||
|
|
||||||
function register (name, filter) {
|
|
||||||
filters[name] = filter
|
|
||||||
}
|
|
||||||
|
|
||||||
function clear () {
|
|
||||||
filters = {}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
construct, register, clear
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-139
@@ -1,139 +0,0 @@
|
|||||||
import strftime from './util/strftime'
|
|
||||||
import * as _ from './util/underscore'
|
|
||||||
import { isTruthy } from './syntax'
|
|
||||||
|
|
||||||
const escapeMap = {
|
|
||||||
'&': '&',
|
|
||||||
'<': '<',
|
|
||||||
'>': '>',
|
|
||||||
'"': '"',
|
|
||||||
"'": '''
|
|
||||||
}
|
|
||||||
const unescapeMap = {
|
|
||||||
'&': '&',
|
|
||||||
'<': '<',
|
|
||||||
'>': '>',
|
|
||||||
'"': '"',
|
|
||||||
''': "'"
|
|
||||||
}
|
|
||||||
|
|
||||||
const filters = {
|
|
||||||
'abs': v => Math.abs(v),
|
|
||||||
'append': (v, arg) => v + arg,
|
|
||||||
'capitalize': str => stringify(str).charAt(0).toUpperCase() + str.slice(1),
|
|
||||||
'ceil': v => Math.ceil(v),
|
|
||||||
'concat': (v, arg) => Array.prototype.concat.call(v, arg),
|
|
||||||
'date': (v, arg) => {
|
|
||||||
let date = v
|
|
||||||
if (v === 'now') {
|
|
||||||
date = new Date()
|
|
||||||
} else if (_.isString(v)) {
|
|
||||||
date = new Date(v)
|
|
||||||
}
|
|
||||||
return isValidDate(date) ? strftime(date, arg) : v
|
|
||||||
},
|
|
||||||
'default': (v, arg) => isTruthy(v) ? v : arg,
|
|
||||||
'divided_by': (v, arg) => v / arg,
|
|
||||||
'downcase': v => v.toLowerCase(),
|
|
||||||
'escape': escape,
|
|
||||||
|
|
||||||
'escape_once': str => escape(unescape(str)),
|
|
||||||
'first': v => v[0],
|
|
||||||
'floor': v => Math.floor(v),
|
|
||||||
'join': (v, arg) => v.join(arg === undefined ? ' ' : arg),
|
|
||||||
'last': v => _.last(v),
|
|
||||||
'lstrip': v => stringify(v).replace(/^\s+/, ''),
|
|
||||||
'map': (arr, arg) => arr.map(v => v[arg]),
|
|
||||||
'minus': bindFixed((v, arg) => v - arg),
|
|
||||||
'modulo': bindFixed((v, arg) => v % arg),
|
|
||||||
'newline_to_br': v => v.replace(/\n/g, '<br />'),
|
|
||||||
'plus': bindFixed((v, arg) => Number(v) + Number(arg)),
|
|
||||||
'prepend': (v, arg) => arg + v,
|
|
||||||
'remove': (v, arg) => v.split(arg).join(''),
|
|
||||||
'remove_first': (v, l) => v.replace(l, ''),
|
|
||||||
'replace': (v, pattern, replacement) =>
|
|
||||||
stringify(v).split(pattern).join(replacement),
|
|
||||||
'replace_first': (v, arg1, arg2) => stringify(v).replace(arg1, arg2),
|
|
||||||
'reverse': v => v.reverse(),
|
|
||||||
'round': (v, arg) => {
|
|
||||||
const amp = Math.pow(10, arg || 0)
|
|
||||||
return Math.round(v * amp, arg) / amp
|
|
||||||
},
|
|
||||||
'rstrip': str => stringify(str).replace(/\s+$/, ''),
|
|
||||||
'size': v => v.length,
|
|
||||||
'slice': (v, begin, length) => {
|
|
||||||
if (length === undefined) length = 1
|
|
||||||
return v.slice(begin, begin + length)
|
|
||||||
},
|
|
||||||
'sort': (v, arg) => v.sort(arg),
|
|
||||||
'split': (v, arg) => stringify(v).split(arg),
|
|
||||||
'strip': (v) => stringify(v).trim(),
|
|
||||||
'strip_html': v => stringify(v).replace(/<script.*?<\/script>|<!--.*?-->|<style.*?<\/style>|<.*?>/g, ''),
|
|
||||||
'strip_newlines': v => stringify(v).replace(/\n/g, ''),
|
|
||||||
'times': (v, arg) => v * arg,
|
|
||||||
'truncate': (v, l, o) => {
|
|
||||||
v = stringify(v)
|
|
||||||
o = (o === undefined) ? '...' : o
|
|
||||||
l = l || 16
|
|
||||||
if (v.length <= l) return v
|
|
||||||
return v.substr(0, l - o.length) + o
|
|
||||||
},
|
|
||||||
'truncatewords': (v, l, o) => {
|
|
||||||
if (o === undefined) o = '...'
|
|
||||||
const arr = v.split(' ')
|
|
||||||
let ret = arr.slice(0, l).join(' ')
|
|
||||||
if (arr.length > l) ret += o
|
|
||||||
return ret
|
|
||||||
},
|
|
||||||
'uniq': function (arr) {
|
|
||||||
const u = {}
|
|
||||||
return (arr || []).filter(val => {
|
|
||||||
if (u.hasOwnProperty(val)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
u[val] = true
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
},
|
|
||||||
'upcase': str => stringify(str).toUpperCase(),
|
|
||||||
'url_decode': x => x.split('+').map(decodeURIComponent).join(' '),
|
|
||||||
'url_encode': x => x.split(' ').map(encodeURIComponent).join('+')
|
|
||||||
}
|
|
||||||
|
|
||||||
function escape (str) {
|
|
||||||
return stringify(str).replace(/&|<|>|"|'/g, m => escapeMap[m])
|
|
||||||
}
|
|
||||||
|
|
||||||
function unescape (str) {
|
|
||||||
return stringify(str).replace(/&(amp|lt|gt|#34|#39);/g, m => unescapeMap[m])
|
|
||||||
}
|
|
||||||
|
|
||||||
function getFixed (v) {
|
|
||||||
const p = (v + '').split('.')
|
|
||||||
return (p.length > 1) ? p[1].length : 0
|
|
||||||
}
|
|
||||||
|
|
||||||
function getMaxFixed (l, r) {
|
|
||||||
return Math.max(getFixed(l), getFixed(r))
|
|
||||||
}
|
|
||||||
|
|
||||||
function stringify (obj) {
|
|
||||||
return obj + ''
|
|
||||||
}
|
|
||||||
|
|
||||||
function bindFixed (cb) {
|
|
||||||
return (l, r) => {
|
|
||||||
const f = getMaxFixed(l, r)
|
|
||||||
return cb(l, r).toFixed(f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function isValidDate (date) {
|
|
||||||
return date instanceof Date && !isNaN(date.getTime())
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function registerAll (liquid, Liquid) {
|
|
||||||
return _.forOwn(filters, (func, name) => liquid.registerFilter(name, func))
|
|
||||||
}
|
|
||||||
|
|
||||||
registerAll.filters = filters
|
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
export interface LiquidOptions {
|
||||||
|
/** `root` is a directory or an array of directories to resolve layouts and includes, as well as the filename passed in when calling `.renderFile()`. If an array, the files are looked up in the order they occur in the array. Defaults to `["."]`*/
|
||||||
|
root?: string | string[]
|
||||||
|
/** `extname` is used to lookup the template file when filepath doesn't include an extension name. Eg: setting to `".html"` will allow including file by basename. Defaults to `""`. */
|
||||||
|
extname?: string
|
||||||
|
/** `cache` indicates whether or not to cache resolved templates. Defaults to `false`. */
|
||||||
|
cache?: boolean
|
||||||
|
/** `dynamicPartials`: if set, treat `<filepath>` parameter in `{%include filepath %}`, `{%layout filepath%}` as a variable, otherwise as a literal value. Defaults to `true`. */
|
||||||
|
dynamicPartials?: boolean
|
||||||
|
/** `strict_filters` is used to enable strict filter existence. If set to `false`, undefined filters will be rendered as empty string. Otherwise, undefined filters will cause an exception. Defaults to `false`. */
|
||||||
|
strict_filters?: boolean
|
||||||
|
/** `strict_variables` is used to enable strict variable derivation. If set to `false`, undefined variables will be rendered as empty string. Otherwise, undefined variables will cause an exception. Defaults to `false`. */
|
||||||
|
strict_variables?: boolean
|
||||||
|
/** `trim_tag_right` is used to strip blank characters (including ` `, `\t`, and `\r`) from the right of tags (`{% %}`) until `\n` (inclusive). Defaults to `false`. */
|
||||||
|
trim_tag_right?: boolean
|
||||||
|
/** `trim_tag_left` is similar to `trim_tag_right`, whereas the `\n` is exclusive. Defaults to `false`. See Whitespace Control for details. */
|
||||||
|
trim_tag_left?: boolean
|
||||||
|
/** ``trim_value_right` is used to strip blank characters (including ` `, `\t`, and `\r`) from the right of values (`{{ }}`) until `\n` (inclusive). Defaults to `false`. */
|
||||||
|
trim_value_right?: boolean
|
||||||
|
/** `trim_value_left` is similar to `trim_value_right`, whereas the `\n` is exclusive. Defaults to `false`. See Whitespace Control for details. */
|
||||||
|
trim_value_left?: boolean
|
||||||
|
/** `greedy` is used to specify whether `trim_left`/`trim_right` is greedy. When set to `true`, all consecutive blank characters including `\n` will be trimed regardless of line breaks. Defaults to `true`. */
|
||||||
|
greedy?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export const defaultOptions: LiquidOptions = {
|
||||||
|
root: ['.'],
|
||||||
|
cache: false,
|
||||||
|
extname: '',
|
||||||
|
dynamicPartials: true,
|
||||||
|
trim_tag_right: false,
|
||||||
|
trim_tag_left: false,
|
||||||
|
trim_value_right: false,
|
||||||
|
trim_value_left: false,
|
||||||
|
greedy: true,
|
||||||
|
strict_filters: false,
|
||||||
|
strict_variables: false
|
||||||
|
}
|
||||||
@@ -1,63 +1,49 @@
|
|||||||
import Scope from './scope'
|
import Scope from './scope/scope'
|
||||||
import * as template from './template'
|
import * as Types from './types'
|
||||||
|
import * as template from 'template'
|
||||||
import * as _ from './util/underscore'
|
import * as _ from './util/underscore'
|
||||||
import assert from './util/assert'
|
import ITemplate from './template/itemplate'
|
||||||
import * as tokenizer from './tokenizer'
|
import * as tokenizer from './parser/tokenizer'
|
||||||
import Render from './render'
|
import Render from './render/render'
|
||||||
import Tag from './tag'
|
import Tag from './template/tag/tag'
|
||||||
import Filter from './filter'
|
import Filter from './template/filter'
|
||||||
import Parser from './parser'
|
import Parser from './parser/parser'
|
||||||
import { isTruthy, isFalsy, evalExp, evalValue } from './syntax'
|
import Value from './template/value'
|
||||||
import { ParseError, TokenizationError, RenderBreakError, AssertionError } from './util/error'
|
import { isTruthy, isFalsy, evalExp, evalValue } from './render/syntax'
|
||||||
import tags from './tags/index'
|
import builtinTags from './builtin/tags'
|
||||||
import filters from './filters'
|
import builtinFilters from './builtin/filters'
|
||||||
|
import { LiquidOptions, defaultOptions } from './liquid-options'
|
||||||
|
|
||||||
export default class Liquid {
|
export default class Liquid {
|
||||||
|
public options: LiquidOptions
|
||||||
private cache: object
|
private cache: object
|
||||||
private options: any
|
private parser: Parser
|
||||||
private tags: any
|
private renderer: Render
|
||||||
private filters: any
|
|
||||||
private parser: any
|
|
||||||
private renderer: any
|
|
||||||
|
|
||||||
constructor (options) {
|
constructor (options: LiquidOptions = {}) {
|
||||||
options = _.assign({
|
options = _.assign({}, defaultOptions, options)
|
||||||
root: ['.'],
|
|
||||||
cache: false,
|
|
||||||
extname: '',
|
|
||||||
dynamicPartials: true,
|
|
||||||
trim_tag_right: false,
|
|
||||||
trim_tag_left: false,
|
|
||||||
trim_value_right: false,
|
|
||||||
trim_value_left: false,
|
|
||||||
greedy: true,
|
|
||||||
strict_filters: false,
|
|
||||||
strict_variables: false
|
|
||||||
}, options)
|
|
||||||
options.root = normalizeStringArray(options.root)
|
options.root = normalizeStringArray(options.root)
|
||||||
|
|
||||||
if (options.cache) {
|
if (options.cache) {
|
||||||
this.cache = {}
|
this.cache = {}
|
||||||
}
|
}
|
||||||
this.options = options
|
this.options = options
|
||||||
this.tags = Tag()
|
this.parser = new Parser(this)
|
||||||
this.filters = Filter(options)
|
this.renderer = new Render()
|
||||||
this.parser = Parser(this.tags, this.filters)
|
|
||||||
this.renderer = Render()
|
|
||||||
|
|
||||||
tags(this, Liquid)
|
_.forOwn(builtinTags, (conf, name) => this.registerTag(name, conf))
|
||||||
filters(this, Liquid)
|
_.forOwn(builtinFilters, (handler, name) => this.registerFilter(name, handler))
|
||||||
}
|
}
|
||||||
parse(html: string, filepath?: string) {
|
parse(html: string, filepath?: string) {
|
||||||
const tokens = tokenizer.parse(html, filepath, this.options)
|
const tokens = tokenizer.parse(html, filepath, this.options)
|
||||||
return this.parser.parse(tokens)
|
return this.parser.parse(tokens)
|
||||||
}
|
}
|
||||||
render(tpl: string, ctx: any, opts: any) {
|
render(tpl: Array<ITemplate>, ctx?: object, opts?: LiquidOptions) {
|
||||||
opts = _.assign({}, this.options, opts)
|
opts = _.assign({}, this.options, opts)
|
||||||
const scope = new Scope(ctx, opts)
|
const scope = new Scope(ctx, opts)
|
||||||
return this.renderer.renderTemplates(tpl, scope)
|
return this.renderer.renderTemplates(tpl, scope)
|
||||||
}
|
}
|
||||||
async parseAndRender(html, ctx, opts) {
|
async parseAndRender(html: string, ctx?: object, opts?: LiquidOptions) {
|
||||||
const tpl = await this.parse(html)
|
const tpl = await this.parse(html)
|
||||||
return this.render(tpl, ctx, opts)
|
return this.render(tpl, ctx, opts)
|
||||||
}
|
}
|
||||||
@@ -68,7 +54,7 @@ export default class Liquid {
|
|||||||
return this.parse(str, filepath)
|
return this.parse(str, filepath)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
async renderFile(file, ctx, opts) {
|
async renderFile(file, ctx?: object, opts?: LiquidOptions) {
|
||||||
opts = _.assign({}, opts)
|
opts = _.assign({}, opts)
|
||||||
const templates = await this.getTemplate(file, opts.root)
|
const templates = await this.getTemplate(file, opts.root)
|
||||||
return this.render(templates, ctx, opts)
|
return this.render(templates, ctx, opts)
|
||||||
@@ -84,25 +70,21 @@ export default class Liquid {
|
|||||||
}
|
}
|
||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
evalValue (str, scope) {
|
evalValue (str: string, scope: Scope) {
|
||||||
const tpl = this.parser.parseValue(str.trim())
|
return new Value(str, this.options.strict_filters).value(scope)
|
||||||
return this.renderer.evalValue(tpl, scope)
|
|
||||||
}
|
}
|
||||||
registerFilter (name, filter) {
|
registerFilter (name, filter) {
|
||||||
return this.filters.register(name, filter)
|
return Filter.register(name, filter)
|
||||||
}
|
}
|
||||||
registerTag (name, tag) {
|
registerTag (name, tag) {
|
||||||
return this.tags.register(name, tag)
|
return Tag.register(name, tag)
|
||||||
}
|
}
|
||||||
plugin (plugin) {
|
plugin (plugin) {
|
||||||
return plugin.call(this, Liquid)
|
return plugin.call(this, Liquid)
|
||||||
}
|
}
|
||||||
express (opts) {
|
express (opts: LiquidOptions = {}) {
|
||||||
opts = opts || {}
|
|
||||||
const self = this
|
const self = this
|
||||||
return function (filePath, ctx, cb) {
|
return function (filePath, ctx, cb) {
|
||||||
assert(_.isArray(this.root) || _.isString(this.root),
|
|
||||||
'illegal views root, are you using express.js?')
|
|
||||||
opts.root = this.root
|
opts.root = this.root
|
||||||
self.renderFile(filePath, ctx, opts).then(html => cb(null, html), cb)
|
self.renderFile(filePath, ctx, opts).then(html => cb(null, html), cb)
|
||||||
}
|
}
|
||||||
@@ -112,16 +94,7 @@ export default class Liquid {
|
|||||||
static isFalsy = isFalsy
|
static isFalsy = isFalsy
|
||||||
static evalExp = evalExp
|
static evalExp = evalExp
|
||||||
static evalValue = evalValue
|
static evalValue = evalValue
|
||||||
static Types = {
|
static Types = Types
|
||||||
ParseError,
|
|
||||||
TokenizationError,
|
|
||||||
RenderBreakError,
|
|
||||||
AssertionError,
|
|
||||||
AssignScope: {},
|
|
||||||
CaptureScope: {},
|
|
||||||
IncrementScope: {},
|
|
||||||
DecrementScope: {}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeStringArray (value) {
|
function normalizeStringArray (value) {
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
export default function (isTruthy) {
|
|
||||||
return {
|
|
||||||
'==': (l, r) => l === r,
|
|
||||||
'!=': (l, r) => l !== r,
|
|
||||||
'>': (l, r) => l !== null && r !== null && l > r,
|
|
||||||
'<': (l, r) => l !== null && r !== null && l < r,
|
|
||||||
'>=': (l, r) => l !== null && r !== null && l >= r,
|
|
||||||
'<=': (l, r) => l !== null && r !== null && l <= r,
|
|
||||||
'contains': (l, r) => {
|
|
||||||
if (!l) return false
|
|
||||||
if (typeof l.indexOf !== 'function') return false
|
|
||||||
return l.indexOf(r) > -1
|
|
||||||
},
|
|
||||||
'and': (l, r) => isTruthy(l) && isTruthy(r),
|
|
||||||
'or': (l, r) => isTruthy(l) || isTruthy(r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-106
@@ -1,106 +0,0 @@
|
|||||||
import * as lexical from './lexical'
|
|
||||||
import { ParseError } from './util/error'
|
|
||||||
import assert from './util/assert'
|
|
||||||
|
|
||||||
export default function (Tag, Filter) {
|
|
||||||
class ParseStream {
|
|
||||||
tokens: Array<any>
|
|
||||||
handlers: object
|
|
||||||
stopRequested: boolean
|
|
||||||
constructor (tokens) {
|
|
||||||
this.tokens = tokens
|
|
||||||
this.handlers = {}
|
|
||||||
}
|
|
||||||
on (name, cb) {
|
|
||||||
this.handlers[name] = cb
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
trigger (event: string, arg?: any) {
|
|
||||||
const h = this.handlers[event]
|
|
||||||
if (typeof h === 'function') {
|
|
||||||
h(arg)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
start () {
|
|
||||||
this.trigger('start')
|
|
||||||
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
|
|
||||||
}
|
|
||||||
const template = parseToken(token, this.tokens)
|
|
||||||
this.trigger('template', template)
|
|
||||||
}
|
|
||||||
if (!this.stopRequested) this.trigger('end')
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
stop () {
|
|
||||||
this.stopRequested = true
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function parse (tokens) {
|
|
||||||
let token
|
|
||||||
const templates = []
|
|
||||||
while ((token = tokens.shift())) {
|
|
||||||
templates.push(parseToken(token, tokens))
|
|
||||||
}
|
|
||||||
return templates
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseToken (token, tokens) {
|
|
||||||
try {
|
|
||||||
let tpl = null
|
|
||||||
if (token.type === 'tag') {
|
|
||||||
tpl = parseTag(token, tokens)
|
|
||||||
} else if (token.type === 'value') {
|
|
||||||
tpl = parseValue(token.value)
|
|
||||||
} else { // token.type === 'html'
|
|
||||||
tpl = token
|
|
||||||
}
|
|
||||||
tpl.token = token
|
|
||||||
return tpl
|
|
||||||
} catch (e) {
|
|
||||||
throw new ParseError(e, token)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseTag (token, tokens) {
|
|
||||||
if (token.name === 'continue' || token.name === 'break') return token
|
|
||||||
return Tag.construct(token, tokens)
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseValue (str) {
|
|
||||||
let match = lexical.matchValue(str)
|
|
||||||
assert(match, `illegal value string: ${str}`)
|
|
||||||
|
|
||||||
const initial = match[0]
|
|
||||||
str = str.substr(match.index + match[0].length)
|
|
||||||
|
|
||||||
const filters = []
|
|
||||||
while ((match = lexical.filter.exec(str))) {
|
|
||||||
filters.push([match[0].trim()])
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
type: 'value',
|
|
||||||
initial: initial,
|
|
||||||
filters: filters.map(str => Filter.construct(str))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseStream (tokens) {
|
|
||||||
return new ParseStream(tokens)
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
parse,
|
|
||||||
parseTag,
|
|
||||||
parseStream,
|
|
||||||
parseValue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import Token from './token'
|
||||||
|
|
||||||
|
export default class DelimitedToken extends Token {
|
||||||
|
trim_left: boolean
|
||||||
|
trim_right: boolean
|
||||||
|
constructor(raw, pos, input, file, line) {
|
||||||
|
super(raw, pos, input, file, line)
|
||||||
|
this.trim_left = raw[2] === '-'
|
||||||
|
this.trim_right = raw[raw.length - 3] === '-'
|
||||||
|
this.value = raw.slice(this.trim_left ? 3 : 2, this.trim_right ? -3 : -2).trim()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import Token from './token'
|
||||||
|
|
||||||
|
export default class HTMLToken extends Token {
|
||||||
|
constructor(str, begin, input, file, line) {
|
||||||
|
super(str, begin, input, file, line)
|
||||||
|
this.type = 'html'
|
||||||
|
this.value = str
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,7 +27,7 @@ export const hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.sour
|
|||||||
export const hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
|
export const hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
|
||||||
|
|
||||||
// full match
|
// full match
|
||||||
export const tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`)
|
export const tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*?)\\s*$`)
|
||||||
export const literalLine = new RegExp(`^${literal.source}$`, 'i')
|
export const literalLine = new RegExp(`^${literal.source}$`, 'i')
|
||||||
export const variableLine = new RegExp(`^${variable.source}$`)
|
export const variableLine = new RegExp(`^${variable.source}$`)
|
||||||
export const numberLine = new RegExp(`^${number.source}$`)
|
export const numberLine = new RegExp(`^${number.source}$`)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import DelimitedToken from './delimited-token'
|
||||||
|
|
||||||
|
export default class OutputToken extends DelimitedToken {
|
||||||
|
constructor(raw, pos, input, file, line) {
|
||||||
|
super(raw, pos, input, file, line)
|
||||||
|
this.type = 'output'
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import Token from 'src/parser/token'
|
||||||
|
import ITemplate from 'src/template/itemplate'
|
||||||
|
|
||||||
|
type parseToken = (token: Token, remainTokens: Array<Token>) => ITemplate
|
||||||
|
type eventHandler = ((arg?: Token | ITemplate) => void)
|
||||||
|
|
||||||
|
export default class ParseStream {
|
||||||
|
private tokens: Array<Token>
|
||||||
|
private handlers: {[key: string]: eventHandler} = {}
|
||||||
|
private stopRequested: boolean
|
||||||
|
private parseToken: parseToken
|
||||||
|
|
||||||
|
constructor (tokens: Array<Token>, parseToken: parseToken) {
|
||||||
|
this.tokens = tokens
|
||||||
|
this.parseToken = parseToken
|
||||||
|
}
|
||||||
|
on (name: string, cb: eventHandler) {
|
||||||
|
this.handlers[name] = cb
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
trigger (event: string, arg?: Token | ITemplate) {
|
||||||
|
const h = this.handlers[event]
|
||||||
|
if (typeof h === 'function') {
|
||||||
|
h(arg)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
start () {
|
||||||
|
this.trigger('start')
|
||||||
|
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
|
||||||
|
}
|
||||||
|
const template = this.parseToken(token, this.tokens)
|
||||||
|
this.trigger('template', template)
|
||||||
|
}
|
||||||
|
if (!this.stopRequested) this.trigger('end')
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
stop () {
|
||||||
|
this.stopRequested = true
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { ParseError } from '../util/error'
|
||||||
|
import Liquid from 'src/liquid'
|
||||||
|
import ParseStream from './parse-stream'
|
||||||
|
import Token from './token'
|
||||||
|
import Tag from 'src/template/tag/tag'
|
||||||
|
import HTMLToken from './html-token'
|
||||||
|
import TagToken from './tag-token'
|
||||||
|
import OutputToken from './output-token'
|
||||||
|
import Output from 'src/template/output'
|
||||||
|
import HTML from 'src/template/html'
|
||||||
|
import Value from 'src/template/value'
|
||||||
|
|
||||||
|
export default class Parser {
|
||||||
|
liquid: Liquid
|
||||||
|
|
||||||
|
constructor(liquid: Liquid) {
|
||||||
|
this.liquid = liquid
|
||||||
|
}
|
||||||
|
parse (tokens: Array<Token>) {
|
||||||
|
let token
|
||||||
|
const templates = []
|
||||||
|
while ((token = tokens.shift())) {
|
||||||
|
templates.push(this.parseToken(token, tokens))
|
||||||
|
}
|
||||||
|
return templates
|
||||||
|
}
|
||||||
|
parseToken (token: Token, remainTokens: Array<Token>) {
|
||||||
|
try {
|
||||||
|
if (token.type === 'tag') {
|
||||||
|
return new Tag(token, remainTokens, this.liquid)
|
||||||
|
}
|
||||||
|
if (token.type === 'output') {
|
||||||
|
return new Output(token, this.liquid.options.strict_filters)
|
||||||
|
}
|
||||||
|
return new HTML(token)
|
||||||
|
} catch (e) {
|
||||||
|
throw new ParseError(e, token)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parseStream (tokens: Array<Token>) {
|
||||||
|
return new ParseStream(tokens, (token, tokens) => this.parseToken(token, tokens))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import DelimitedToken from './delimited-token'
|
||||||
|
import { TokenizationError } from 'src/util/error'
|
||||||
|
import * as lexical from './lexical'
|
||||||
|
|
||||||
|
export default class TagToken extends DelimitedToken {
|
||||||
|
name: string
|
||||||
|
args: string
|
||||||
|
constructor(raw, pos, input, file, line) {
|
||||||
|
super(raw, pos, input, file, line)
|
||||||
|
this.type = 'tag'
|
||||||
|
const match = this.value.match(lexical.tagLine)
|
||||||
|
if (!match) {
|
||||||
|
throw new TokenizationError(`illegal tag syntax`, this)
|
||||||
|
}
|
||||||
|
this.name = match[1]
|
||||||
|
this.args = match[2]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { last, isArray } from './util/underscore'
|
import { last, isArray } from '../util/underscore'
|
||||||
|
|
||||||
function domResolve (root, path) {
|
function domResolve (root, path) {
|
||||||
const base = document.createElement('base')
|
const base = document.createElement('base')
|
||||||
@@ -33,12 +33,12 @@ export function resolve (filepath, root, options) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function read (url) {
|
export async function read (url: string): Promise<string> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const xhr = new XMLHttpRequest()
|
const xhr = new XMLHttpRequest()
|
||||||
xhr.onload = () => {
|
xhr.onload = () => {
|
||||||
if (xhr.status >= 200 && xhr.status < 300) {
|
if (xhr.status >= 200 && xhr.status < 300) {
|
||||||
resolve(xhr.responseText)
|
resolve(xhr.responseText as string)
|
||||||
} else {
|
} else {
|
||||||
reject(new Error(xhr.statusText))
|
reject(new Error(xhr.statusText))
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import * as _ from './util/underscore'
|
import * as _ from '../util/underscore'
|
||||||
import * as path from 'path'
|
import * as path from 'path'
|
||||||
import { anySeries } from './util/promise'
|
import { anySeries } from '../util/promise'
|
||||||
import * as fs from 'fs'
|
import * as fs from 'fs'
|
||||||
|
|
||||||
const statFileAsync = <(filepath: string) => Promise<object>>_.promisify(fs.stat)
|
const statFileAsync = <(filepath: string) => Promise<object>>_.promisify(fs.stat)
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
export default class Token {
|
||||||
|
type: string
|
||||||
|
line: number
|
||||||
|
raw: string
|
||||||
|
input: string
|
||||||
|
file: string
|
||||||
|
value: string
|
||||||
|
constructor(raw, pos, input, file, line) {
|
||||||
|
this.line = line
|
||||||
|
this.raw = raw
|
||||||
|
this.input = input
|
||||||
|
this.file = file
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import whiteSpaceCtrl from './whitespace-ctrl'
|
||||||
|
import HTMLToken from './html-token'
|
||||||
|
import TagToken from './tag-token'
|
||||||
|
import OutputToken from './output-token'
|
||||||
|
|
||||||
|
enum ParseState { HTML, OUTPUT, TAG }
|
||||||
|
|
||||||
|
export function parse (input: string, file?: string, options?) {
|
||||||
|
const tokens = []
|
||||||
|
let p = 0
|
||||||
|
let line = 1
|
||||||
|
let state = ParseState.HTML
|
||||||
|
let buffer = ''
|
||||||
|
let bufferBegin = 0
|
||||||
|
|
||||||
|
while(p < input.length) {
|
||||||
|
if (input[p] === '\n') line++
|
||||||
|
const bin = input.substr(p, 2)
|
||||||
|
if (state === ParseState.HTML) {
|
||||||
|
if (bin === '{{' || bin === '{%') {
|
||||||
|
if (buffer) tokens.push(new HTMLToken(buffer, bufferBegin, input, file, line))
|
||||||
|
buffer = bin
|
||||||
|
bufferBegin = p
|
||||||
|
p += 2
|
||||||
|
state = bin === '{{' ? ParseState.OUTPUT : ParseState.TAG
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (state === ParseState.OUTPUT && bin === '}}') {
|
||||||
|
buffer += '}}'
|
||||||
|
tokens.push(new OutputToken(buffer, bufferBegin, input, file, line))
|
||||||
|
p += 2
|
||||||
|
buffer = ''
|
||||||
|
bufferBegin = p
|
||||||
|
state = ParseState.HTML
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
else if (bin === '%}') {
|
||||||
|
buffer += '%}'
|
||||||
|
tokens.push(new TagToken(buffer, bufferBegin, input, file, line))
|
||||||
|
p += 2
|
||||||
|
buffer = ''
|
||||||
|
bufferBegin = p
|
||||||
|
state = ParseState.HTML
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
buffer += input[p++]
|
||||||
|
}
|
||||||
|
if (buffer) tokens.push(new HTMLToken(buffer, bufferBegin, input, file, line))
|
||||||
|
|
||||||
|
whiteSpaceCtrl(tokens, options)
|
||||||
|
return tokens
|
||||||
|
}
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
import { assign } from './util/underscore'
|
import { assign } from 'src/util/underscore'
|
||||||
|
import TagToken from './tag-token'
|
||||||
|
import OutputToken from './output-token'
|
||||||
|
import HTMLToken from './html-token'
|
||||||
|
|
||||||
export default function whiteSpaceCtrl (tokens, options) {
|
export default function whiteSpaceCtrl (tokens, options) {
|
||||||
options = assign({ greedy: true }, options)
|
options = assign({ greedy: true }, options)
|
||||||
@@ -21,13 +24,13 @@ export default function whiteSpaceCtrl (tokens, options) {
|
|||||||
function shouldTrimLeft (token, inRaw, options) {
|
function shouldTrimLeft (token, inRaw, options) {
|
||||||
if (inRaw) return false
|
if (inRaw) return false
|
||||||
if (token.type === 'tag') return token.trim_left || options.trim_tag_left
|
if (token.type === 'tag') return token.trim_left || options.trim_tag_left
|
||||||
if (token.type === 'value') return token.trim_left || options.trim_value_left
|
if (token.type === 'output') return token.trim_left || options.trim_value_left
|
||||||
}
|
}
|
||||||
|
|
||||||
function shouldTrimRight (token, inRaw, options) {
|
function shouldTrimRight (token, inRaw, options) {
|
||||||
if (inRaw) return false
|
if (inRaw) return false
|
||||||
if (token.type === 'tag') return token.trim_right || options.trim_tag_right
|
if (token.type === 'tag') return token.trim_right || options.trim_tag_right
|
||||||
if (token.type === 'value') return token.trim_right || options.trim_value_right
|
if (token.type === 'output') return token.trim_right || options.trim_value_right
|
||||||
}
|
}
|
||||||
|
|
||||||
function trimLeft (token, greedy) {
|
function trimLeft (token, greedy) {
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
import { evalExp } from './syntax'
|
|
||||||
import { RenderBreakError, RenderError } from './util/error'
|
|
||||||
import { stringify, create } from './util/underscore'
|
|
||||||
import assert from './util/assert'
|
|
||||||
|
|
||||||
const render = {
|
|
||||||
renderTemplates: async function (templates, scope) {
|
|
||||||
assert(scope, 'unable to evalTemplates: scope undefined')
|
|
||||||
|
|
||||||
let html = ''
|
|
||||||
for (const tpl of templates) {
|
|
||||||
try {
|
|
||||||
html += await renderTemplate.call(this, tpl)
|
|
||||||
} catch (e) {
|
|
||||||
if (e instanceof RenderBreakError) {
|
|
||||||
e.resolvedHTML = html
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
throw e instanceof RenderError ? e : new RenderError(e, tpl)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return html
|
|
||||||
|
|
||||||
async function renderTemplate (template) {
|
|
||||||
if (template.type === 'tag') {
|
|
||||||
const partial = await this.renderTag(template, scope)
|
|
||||||
return partial === undefined ? '' : partial
|
|
||||||
}
|
|
||||||
if (template.type === 'value') {
|
|
||||||
return this.renderValue(template, scope)
|
|
||||||
}
|
|
||||||
return template.value
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
renderTag: async function (template, scope) {
|
|
||||||
if (template.name === 'continue') {
|
|
||||||
throw new RenderBreakError('continue')
|
|
||||||
}
|
|
||||||
if (template.name === 'break') {
|
|
||||||
throw new RenderBreakError('break')
|
|
||||||
}
|
|
||||||
return template.render(scope)
|
|
||||||
},
|
|
||||||
|
|
||||||
renderValue: async function (template, scope) {
|
|
||||||
const partial = this.evalValue(template, scope)
|
|
||||||
return partial === undefined ? '' : stringify(partial)
|
|
||||||
},
|
|
||||||
|
|
||||||
evalValue: function (template, scope) {
|
|
||||||
assert(scope, 'unable to evalValue: scope undefined')
|
|
||||||
return template.filters.reduce(
|
|
||||||
(prev, filter) => filter.render(prev, scope),
|
|
||||||
evalExp(template.initial, scope))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function () {
|
|
||||||
const instance = create(render)
|
|
||||||
return instance
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { stringify, create } from 'src/util/underscore'
|
||||||
|
import { RenderBreakError, RenderError } from 'src/util/error'
|
||||||
|
import assert from 'src/util/assert'
|
||||||
|
import Scope from 'src/scope/scope'
|
||||||
|
|
||||||
|
export default class Render {
|
||||||
|
async renderTemplates (templates, scope) {
|
||||||
|
assert(scope, 'unable to evalTemplates: scope undefined')
|
||||||
|
|
||||||
|
let html = ''
|
||||||
|
for (const tpl of templates) {
|
||||||
|
try {
|
||||||
|
html += await tpl.render(scope)
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof RenderBreakError) {
|
||||||
|
e.resolvedHTML = html
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
throw e instanceof RenderError ? e : new RenderError(e, tpl)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return html
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,21 @@
|
|||||||
import Operators from './operators'
|
import * as lexical from '../parser/lexical'
|
||||||
import * as lexical from './lexical'
|
import assert from '../util/assert'
|
||||||
import assert from './util/assert'
|
|
||||||
|
|
||||||
const operators = Operators(isTruthy)
|
const operators = {
|
||||||
|
'==': (l, r) => l === r,
|
||||||
|
'!=': (l, r) => l !== r,
|
||||||
|
'>': (l, r) => l !== null && r !== null && l > r,
|
||||||
|
'<': (l, r) => l !== null && r !== null && l < r,
|
||||||
|
'>=': (l, r) => l !== null && r !== null && l >= r,
|
||||||
|
'<=': (l, r) => l !== null && r !== null && l <= r,
|
||||||
|
'contains': (l, r) => {
|
||||||
|
if (!l) return false
|
||||||
|
if (typeof l.indexOf !== 'function') return false
|
||||||
|
return l.indexOf(r) > -1
|
||||||
|
},
|
||||||
|
'and': (l, r) => isTruthy(l) && isTruthy(r),
|
||||||
|
'or': (l, r) => isTruthy(l) || isTruthy(r)
|
||||||
|
}
|
||||||
|
|
||||||
export function evalExp (exp, scope) {
|
export function evalExp (exp, scope) {
|
||||||
assert(scope, 'unable to evalExp: scope undefined')
|
assert(scope, 'unable to evalExp: scope undefined')
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
enum BlockMode {
|
||||||
|
/* store rendered html into blocks */
|
||||||
|
OUTPUT,
|
||||||
|
/* output rendered html directly */
|
||||||
|
STORE
|
||||||
|
}
|
||||||
|
|
||||||
|
export default BlockMode
|
||||||
@@ -1,38 +1,32 @@
|
|||||||
import * as _ from './util/underscore'
|
import * as _ from '../util/underscore'
|
||||||
import * as lexical from './lexical'
|
import * as lexical from '../parser/lexical'
|
||||||
import assert from './util/assert'
|
import assert from '../util/assert'
|
||||||
|
import { LiquidOptions, defaultOptions } from '../liquid-options'
|
||||||
interface ScopeOptions {
|
import BlockMode from './block-mode'
|
||||||
dynamicPartials: boolean
|
|
||||||
strict_variables: boolean
|
|
||||||
strict_filters: boolean
|
|
||||||
blocks: object
|
|
||||||
root: Array<string>
|
|
||||||
}
|
|
||||||
|
|
||||||
export default class Scope {
|
export default class Scope {
|
||||||
opts: ScopeOptions
|
opts: LiquidOptions
|
||||||
contexts: Array<object>
|
contexts: Array<object>
|
||||||
constructor (ctx = {}, opts?: any) {
|
blocks: object = {}
|
||||||
const defaultOptions: ScopeOptions = {
|
blockMode: BlockMode = BlockMode.OUTPUT
|
||||||
|
constructor (ctx: object = {}, opts: LiquidOptions = defaultOptions) {
|
||||||
|
this.opts = _.assign({
|
||||||
dynamicPartials: true,
|
dynamicPartials: true,
|
||||||
strict_variables: false,
|
strict_variables: false,
|
||||||
strict_filters: false,
|
strict_filters: false,
|
||||||
blocks: {},
|
|
||||||
root: []
|
root: []
|
||||||
}
|
} , opts)
|
||||||
this.opts = _.assign(defaultOptions, opts)
|
|
||||||
this.contexts = [ctx || {}]
|
this.contexts = [ctx || {}]
|
||||||
}
|
}
|
||||||
getAll () {
|
getAll () {
|
||||||
return this.contexts.reduce((ctx, val) => _.assign(ctx, val), _.create(null))
|
return this.contexts.reduce((ctx, val) => _.assign(ctx, val), _.create(null))
|
||||||
}
|
}
|
||||||
get (path) {
|
get (path: string): any {
|
||||||
const paths = this.propertyAccessSeq(path)
|
const paths = this.propertyAccessSeq(path)
|
||||||
const scope = this.findContextFor(paths[0]) || _.last(this.contexts)
|
const scope = this.findContextFor(paths[0]) || _.last(this.contexts)
|
||||||
return paths.reduce((value, key) => this.readProperty(value, key), scope)
|
return paths.reduce((value, key) => this.readProperty(value, key), scope)
|
||||||
}
|
}
|
||||||
set (path, v) {
|
set (path: string, v: any): void {
|
||||||
const paths = this.propertyAccessSeq(path)
|
const paths = this.propertyAccessSeq(path)
|
||||||
let scope = this.findContextFor(paths[0]) || _.last(this.contexts)
|
let scope = this.findContextFor(paths[0]) || _.last(this.contexts)
|
||||||
paths.some((key, i) => {
|
paths.some((key, i) => {
|
||||||
@@ -49,13 +43,13 @@ export default class Scope {
|
|||||||
scope = scope[key]
|
scope = scope[key]
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
unshift (ctx) {
|
unshift (ctx: object): any {
|
||||||
return this.contexts.unshift(ctx)
|
return this.contexts.unshift(ctx)
|
||||||
}
|
}
|
||||||
push (ctx) {
|
push (ctx: object): any {
|
||||||
return this.contexts.push(ctx)
|
return this.contexts.push(ctx)
|
||||||
}
|
}
|
||||||
pop (ctx) {
|
pop (ctx?: object): object {
|
||||||
if (!arguments.length) {
|
if (!arguments.length) {
|
||||||
return this.contexts.pop()
|
return this.contexts.pop()
|
||||||
}
|
}
|
||||||
@@ -65,7 +59,7 @@ export default class Scope {
|
|||||||
}
|
}
|
||||||
return this.contexts.splice(i, 1)[0]
|
return this.contexts.splice(i, 1)[0]
|
||||||
}
|
}
|
||||||
findContextFor (key, filter = (arg => true)) {
|
findContextFor (key: string, filter = (arg => true)) {
|
||||||
for (let i = this.contexts.length - 1; i >= 0; i--) {
|
for (let i = this.contexts.length - 1; i >= 0; i--) {
|
||||||
const candidate = this.contexts[i]
|
const candidate = this.contexts[i]
|
||||||
if (!filter(candidate)) continue
|
if (!filter(candidate)) continue
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export class CaptureScope {}
|
||||||
|
export class AssignScope {}
|
||||||
|
export class IncrementScope {}
|
||||||
|
export class DecrementScope {}
|
||||||
-63
@@ -1,63 +0,0 @@
|
|||||||
import { hashCapture } from './lexical'
|
|
||||||
import { create } from './util/underscore'
|
|
||||||
import { evalValue } from './syntax'
|
|
||||||
import assert from './util/assert'
|
|
||||||
|
|
||||||
function hash (markup, scope) {
|
|
||||||
const obj = {}
|
|
||||||
let match
|
|
||||||
hashCapture.lastIndex = 0
|
|
||||||
while ((match = hashCapture.exec(markup))) {
|
|
||||||
const k = match[1]
|
|
||||||
const v = match[2]
|
|
||||||
obj[k] = evalValue(v, scope)
|
|
||||||
}
|
|
||||||
return obj
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function () {
|
|
||||||
let tagImpls = {}
|
|
||||||
|
|
||||||
const _tagInstance = {
|
|
||||||
render: async function (scope) {
|
|
||||||
const obj = hash(this.token.args, scope)
|
|
||||||
const impl = this.tagImpl
|
|
||||||
if (typeof impl.render !== 'function') {
|
|
||||||
return ''
|
|
||||||
}
|
|
||||||
return impl.render(scope, obj)
|
|
||||||
},
|
|
||||||
parse: function (token, tokens) {
|
|
||||||
this.type = 'tag'
|
|
||||||
this.token = token
|
|
||||||
this.name = token.name
|
|
||||||
|
|
||||||
const tagImpl = tagImpls[this.name]
|
|
||||||
assert(tagImpl, `tag ${this.name} not found`)
|
|
||||||
this.tagImpl = create(tagImpl)
|
|
||||||
if (this.tagImpl.parse) {
|
|
||||||
this.tagImpl.parse(token, tokens)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function register (name, tag) {
|
|
||||||
tagImpls[name] = tag
|
|
||||||
}
|
|
||||||
|
|
||||||
function construct (token, tokens) {
|
|
||||||
const instance = create(_tagInstance)
|
|
||||||
instance.parse(token, tokens)
|
|
||||||
return instance
|
|
||||||
}
|
|
||||||
|
|
||||||
function clear () {
|
|
||||||
tagImpls = {}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
construct,
|
|
||||||
register,
|
|
||||||
clear
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
import assert from '../util/assert'
|
|
||||||
import { identifier } from '../lexical'
|
|
||||||
import { create } from '../util/underscore'
|
|
||||||
|
|
||||||
export default function (liquid, Liquid) {
|
|
||||||
const re = new RegExp(`(${identifier.source})\\s*=([^]*)`)
|
|
||||||
const { AssignScope } = Liquid.Types
|
|
||||||
|
|
||||||
liquid.registerTag('assign', {
|
|
||||||
parse: function (token) {
|
|
||||||
const match = token.args.match(re)
|
|
||||||
assert(match, `illegal token ${token.raw}`)
|
|
||||||
this.key = match[1]
|
|
||||||
this.value = match[2]
|
|
||||||
},
|
|
||||||
render: function (scope) {
|
|
||||||
const ctx = create(AssignScope)
|
|
||||||
ctx[this.key] = liquid.evalValue(this.value, scope)
|
|
||||||
scope.push(ctx)
|
|
||||||
return Promise.resolve('')
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import assert from '../util/assert'
|
|
||||||
import { create } from '../util/underscore'
|
|
||||||
import { identifier } from '../lexical'
|
|
||||||
|
|
||||||
export default function (liquid, Liquid) {
|
|
||||||
const re = new RegExp(`(${identifier.source})`)
|
|
||||||
const { CaptureScope } = Liquid.Types
|
|
||||||
|
|
||||||
liquid.registerTag('capture', {
|
|
||||||
parse: function (tagToken, remainTokens) {
|
|
||||||
const match = tagToken.args.match(re)
|
|
||||||
assert(match, `${tagToken.args} not valid identifier`)
|
|
||||||
|
|
||||||
this.variable = match[1]
|
|
||||||
this.templates = []
|
|
||||||
|
|
||||||
const stream = liquid.parser.parseStream(remainTokens)
|
|
||||||
stream.on('tag:endcapture', token => stream.stop())
|
|
||||||
.on('template', tpl => this.templates.push(tpl))
|
|
||||||
.on('end', x => {
|
|
||||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
|
||||||
})
|
|
||||||
stream.start()
|
|
||||||
},
|
|
||||||
render: async function (scope, hash) {
|
|
||||||
const html = await liquid.renderer.renderTemplates(this.templates, scope)
|
|
||||||
const ctx = create(CaptureScope)
|
|
||||||
ctx[this.variable] = html
|
|
||||||
scope.push(ctx)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
export default function (liquid, Liquid) {
|
|
||||||
liquid.registerTag('case', {
|
|
||||||
|
|
||||||
parse: function (tagToken, remainTokens) {
|
|
||||||
this.cond = tagToken.args
|
|
||||||
this.cases = []
|
|
||||||
this.elseTemplates = []
|
|
||||||
|
|
||||||
let p = []
|
|
||||||
const stream = liquid.parser.parseStream(remainTokens)
|
|
||||||
.on('tag:when', token => {
|
|
||||||
this.cases.push({
|
|
||||||
val: token.args,
|
|
||||||
templates: p = []
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.on('tag:else', () => (p = this.elseTemplates))
|
|
||||||
.on('tag:endcase', token => stream.stop())
|
|
||||||
.on('template', tpl => p.push(tpl))
|
|
||||||
.on('end', x => {
|
|
||||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
|
||||||
})
|
|
||||||
|
|
||||||
stream.start()
|
|
||||||
},
|
|
||||||
|
|
||||||
render: function (scope, hash) {
|
|
||||||
for (let i = 0; i < this.cases.length; i++) {
|
|
||||||
const branch = this.cases[i]
|
|
||||||
const val = Liquid.evalExp(branch.val, scope)
|
|
||||||
const cond = Liquid.evalExp(this.cond, scope)
|
|
||||||
if (val === cond) {
|
|
||||||
return liquid.renderer.renderTemplates(branch.templates, scope)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
export default function (liquid) {
|
|
||||||
liquid.registerTag('comment', {
|
|
||||||
parse: function (tagToken, remainTokens) {
|
|
||||||
const stream = liquid.parser.parseStream(remainTokens)
|
|
||||||
stream
|
|
||||||
.on('token', token => {
|
|
||||||
if (token.name === 'endcomment') stream.stop()
|
|
||||||
})
|
|
||||||
.on('end', x => {
|
|
||||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
|
||||||
})
|
|
||||||
stream.start()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
import assert from '../util/assert'
|
|
||||||
import { value as rValue } from '../lexical'
|
|
||||||
|
|
||||||
export default function (liquid, Liquid) {
|
|
||||||
const groupRE = new RegExp(`^(?:(${rValue.source})\\s*:\\s*)?(.*)$`)
|
|
||||||
const candidatesRE = new RegExp(rValue.source, 'g')
|
|
||||||
|
|
||||||
liquid.registerTag('cycle', {
|
|
||||||
|
|
||||||
parse: function (tagToken, remainTokens) {
|
|
||||||
let match = groupRE.exec(tagToken.args)
|
|
||||||
assert(match, `illegal tag: ${tagToken.raw}`)
|
|
||||||
|
|
||||||
this.group = match[1] || ''
|
|
||||||
const candidates = match[2]
|
|
||||||
|
|
||||||
this.candidates = []
|
|
||||||
|
|
||||||
while ((match = candidatesRE.exec(candidates))) {
|
|
||||||
this.candidates.push(match[0])
|
|
||||||
}
|
|
||||||
assert(this.candidates.length, `empty candidates: ${tagToken.raw}`)
|
|
||||||
},
|
|
||||||
|
|
||||||
render: function (scope, hash) {
|
|
||||||
const group = Liquid.evalValue(this.group, scope)
|
|
||||||
const fingerprint = `cycle:${group}:` + this.candidates.join(',')
|
|
||||||
|
|
||||||
const groups = scope.opts.groups = scope.opts.groups || {}
|
|
||||||
let idx = groups[fingerprint]
|
|
||||||
|
|
||||||
if (idx === undefined) {
|
|
||||||
idx = groups[fingerprint] = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
const candidate = this.candidates[idx]
|
|
||||||
idx = (idx + 1) % this.candidates.length
|
|
||||||
groups[fingerprint] = idx
|
|
||||||
|
|
||||||
return Liquid.evalValue(candidate, scope)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import { create } from '../util/underscore'
|
|
||||||
import assert from '../util/assert'
|
|
||||||
import { identifier } from '../lexical'
|
|
||||||
|
|
||||||
export default function (liquid, Liquid) {
|
|
||||||
const { CaptureScope, AssignScope, DecrementScope } = Liquid.Types
|
|
||||||
|
|
||||||
liquid.registerTag('decrement', {
|
|
||||||
parse: function (token) {
|
|
||||||
const match = token.args.match(identifier)
|
|
||||||
assert(match, `illegal identifier ${token.args}`)
|
|
||||||
this.variable = match[0]
|
|
||||||
},
|
|
||||||
render: function (scope, hash) {
|
|
||||||
let context = scope.findContextFor(
|
|
||||||
this.variable,
|
|
||||||
ctx => {
|
|
||||||
const proto = Object.getPrototypeOf(ctx)
|
|
||||||
return proto !== CaptureScope && proto !== AssignScope
|
|
||||||
}
|
|
||||||
)
|
|
||||||
if (!context) {
|
|
||||||
context = create(DecrementScope)
|
|
||||||
scope.unshift(context)
|
|
||||||
}
|
|
||||||
if (typeof context[this.variable] !== 'number') {
|
|
||||||
context[this.variable] = 0
|
|
||||||
}
|
|
||||||
return --context[this.variable]
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
import { mapSeries } from '../util/promise'
|
|
||||||
import { isString, isObject, isArray } from '../util/underscore'
|
|
||||||
import assert from '../util/assert'
|
|
||||||
import { identifier, value, hash } from '../lexical'
|
|
||||||
|
|
||||||
export default function (liquid, Liquid) {
|
|
||||||
const RenderBreakError = Liquid.Types.RenderBreakError
|
|
||||||
const re = new RegExp(`^(${identifier.source})\\s+in\\s+` +
|
|
||||||
`(${value.source})` +
|
|
||||||
`(?:\\s+${hash.source})*` +
|
|
||||||
`(?:\\s+(reversed))?` +
|
|
||||||
`(?:\\s+${hash.source})*$`)
|
|
||||||
|
|
||||||
liquid.registerTag('for', { parse, render })
|
|
||||||
|
|
||||||
function parse (tagToken, remainTokens) {
|
|
||||||
const match = re.exec(tagToken.args)
|
|
||||||
assert(match, `illegal tag: ${tagToken.raw}`)
|
|
||||||
this.variable = match[1]
|
|
||||||
this.collection = match[2]
|
|
||||||
this.reversed = !!match[3]
|
|
||||||
|
|
||||||
this.templates = []
|
|
||||||
this.elseTemplates = []
|
|
||||||
|
|
||||||
let p
|
|
||||||
const stream = liquid.parser.parseStream(remainTokens)
|
|
||||||
.on('start', () => (p = this.templates))
|
|
||||||
.on('tag:else', () => (p = this.elseTemplates))
|
|
||||||
.on('tag:endfor', () => stream.stop())
|
|
||||||
.on('template', tpl => p.push(tpl))
|
|
||||||
.on('end', () => {
|
|
||||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
|
||||||
})
|
|
||||||
|
|
||||||
stream.start()
|
|
||||||
}
|
|
||||||
async function render (scope, hash) {
|
|
||||||
let collection = Liquid.evalExp(this.collection, scope)
|
|
||||||
|
|
||||||
if (!isArray(collection)) {
|
|
||||||
if (isString(collection) && collection.length > 0) {
|
|
||||||
collection = [collection]
|
|
||||||
} else if (isObject(collection)) {
|
|
||||||
collection = Object.keys(collection).map((key) => [key, collection[key]])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!isArray(collection) || !collection.length) {
|
|
||||||
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
|
||||||
}
|
|
||||||
|
|
||||||
const offset = hash.offset || 0
|
|
||||||
const limit = (hash.limit === undefined) ? collection.length : hash.limit
|
|
||||||
|
|
||||||
collection = collection.slice(offset, offset + limit)
|
|
||||||
if (this.reversed) collection.reverse()
|
|
||||||
|
|
||||||
const contexts = collection.map((item, i) => {
|
|
||||||
const ctx = {}
|
|
||||||
ctx[this.variable] = item
|
|
||||||
ctx.forloop = {
|
|
||||||
first: i === 0,
|
|
||||||
index: i + 1,
|
|
||||||
index0: i,
|
|
||||||
last: i === collection.length - 1,
|
|
||||||
length: collection.length,
|
|
||||||
rindex: collection.length - i,
|
|
||||||
rindex0: collection.length - i - 1
|
|
||||||
}
|
|
||||||
return ctx
|
|
||||||
})
|
|
||||||
|
|
||||||
let html = ''
|
|
||||||
let finished = false
|
|
||||||
await mapSeries(contexts, async context => {
|
|
||||||
if (finished) return
|
|
||||||
|
|
||||||
scope.push(context)
|
|
||||||
try {
|
|
||||||
html += await liquid.renderer.renderTemplates(this.templates, scope)
|
|
||||||
} catch (e) {
|
|
||||||
if (e instanceof RenderBreakError) {
|
|
||||||
html += e.resolvedHTML
|
|
||||||
if (e.message === 'break') {
|
|
||||||
finished = true
|
|
||||||
}
|
|
||||||
} else throw e
|
|
||||||
}
|
|
||||||
scope.pop(context)
|
|
||||||
})
|
|
||||||
return html
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
export default function (liquid, Liquid) {
|
|
||||||
liquid.registerTag('if', {
|
|
||||||
|
|
||||||
parse: function (tagToken, remainTokens) {
|
|
||||||
this.branches = []
|
|
||||||
this.elseTemplates = []
|
|
||||||
|
|
||||||
let p
|
|
||||||
const stream = liquid.parser.parseStream(remainTokens)
|
|
||||||
.on('start', () => this.branches.push({
|
|
||||||
cond: tagToken.args,
|
|
||||||
templates: (p = [])
|
|
||||||
}))
|
|
||||||
.on('tag:elsif', token => {
|
|
||||||
this.branches.push({
|
|
||||||
cond: token.args,
|
|
||||||
templates: p = []
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.on('tag:else', () => (p = this.elseTemplates))
|
|
||||||
.on('tag:endif', token => stream.stop())
|
|
||||||
.on('template', tpl => p.push(tpl))
|
|
||||||
.on('end', x => {
|
|
||||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
|
||||||
})
|
|
||||||
|
|
||||||
stream.start()
|
|
||||||
},
|
|
||||||
|
|
||||||
render: function (scope, hash) {
|
|
||||||
for (const branch of this.branches) {
|
|
||||||
const cond = Liquid.evalExp(branch.cond, scope)
|
|
||||||
if (Liquid.isTruthy(cond)) {
|
|
||||||
return liquid.renderer.renderTemplates(branch.templates, scope)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
import assert from '../util/assert'
|
|
||||||
import { value, quotedLine } from '../lexical'
|
|
||||||
|
|
||||||
const staticFileRE = /[^\s,]+/
|
|
||||||
|
|
||||||
export default function (liquid, Liquid) {
|
|
||||||
const withRE = new RegExp(`with\\s+(${value.source})`)
|
|
||||||
|
|
||||||
liquid.registerTag('include', {
|
|
||||||
parse: function (token) {
|
|
||||||
let match = staticFileRE.exec(token.args)
|
|
||||||
if (match) {
|
|
||||||
this.staticValue = match[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
match = value.exec(token.args)
|
|
||||||
if (match) {
|
|
||||||
this.value = match[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
match = withRE.exec(token.args)
|
|
||||||
if (match) {
|
|
||||||
this.with = match[1]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
render: async function (scope, hash) {
|
|
||||||
let filepath
|
|
||||||
if (scope.opts.dynamicPartials) {
|
|
||||||
if (quotedLine.exec(this.value)) {
|
|
||||||
const template = this.value.slice(1, -1)
|
|
||||||
filepath = await liquid.parseAndRender(template, scope.getAll(), scope.opts)
|
|
||||||
} else {
|
|
||||||
filepath = Liquid.evalValue(this.value, scope)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
filepath = this.staticValue
|
|
||||||
}
|
|
||||||
assert(filepath, `cannot include with empty filename`)
|
|
||||||
|
|
||||||
const originBlocks = scope.opts.blocks
|
|
||||||
const originBlockMode = scope.opts.blockMode
|
|
||||||
|
|
||||||
scope.opts.blocks = {}
|
|
||||||
scope.opts.blockMode = 'output'
|
|
||||||
if (this.with) {
|
|
||||||
hash[filepath] = Liquid.evalValue(this.with, scope)
|
|
||||||
}
|
|
||||||
const templates = await liquid.getTemplate(filepath, scope.opts.root)
|
|
||||||
scope.push(hash)
|
|
||||||
const html = await liquid.renderer.renderTemplates(templates, scope)
|
|
||||||
scope.pop(hash)
|
|
||||||
scope.opts.blocks = originBlocks
|
|
||||||
scope.opts.blockMode = originBlockMode
|
|
||||||
return html
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
import assert from '../util/assert'
|
|
||||||
import { create } from '../util/underscore'
|
|
||||||
import { identifier } from '../lexical'
|
|
||||||
|
|
||||||
export default function (liquid, Liquid) {
|
|
||||||
const { CaptureScope, AssignScope, IncrementScope } = Liquid.Types
|
|
||||||
|
|
||||||
liquid.registerTag('increment', {
|
|
||||||
parse: function (token) {
|
|
||||||
const match = token.args.match(identifier)
|
|
||||||
assert(match, `illegal identifier ${token.args}`)
|
|
||||||
this.variable = match[0]
|
|
||||||
},
|
|
||||||
render: function (scope, hash) {
|
|
||||||
let context = scope.findContextFor(
|
|
||||||
this.variable,
|
|
||||||
ctx => {
|
|
||||||
const proto = Object.getPrototypeOf(ctx)
|
|
||||||
return proto !== CaptureScope && proto !== AssignScope
|
|
||||||
}
|
|
||||||
)
|
|
||||||
if (!context) {
|
|
||||||
context = create(IncrementScope)
|
|
||||||
scope.unshift(context)
|
|
||||||
}
|
|
||||||
if (typeof context[this.variable] !== 'number') {
|
|
||||||
context[this.variable] = 0
|
|
||||||
}
|
|
||||||
const val = context[this.variable]
|
|
||||||
context[this.variable]++
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import For from './for'
|
|
||||||
import Assign from './assign'
|
|
||||||
import Capture from './capture'
|
|
||||||
import Case from './case'
|
|
||||||
import Comment from './comment'
|
|
||||||
import Include from './include'
|
|
||||||
import Decrement from './decrement'
|
|
||||||
import Cycle from './cycle'
|
|
||||||
import If from './if'
|
|
||||||
import Increment from './increment'
|
|
||||||
import Layout from './layout'
|
|
||||||
import Raw from './raw'
|
|
||||||
import Tablerow from './tablerow'
|
|
||||||
import Unless from './unless'
|
|
||||||
|
|
||||||
export default function (engine, Liquid) {
|
|
||||||
Assign(engine, Liquid)
|
|
||||||
Capture(engine, Liquid)
|
|
||||||
Case(engine, Liquid)
|
|
||||||
Comment(engine, Liquid)
|
|
||||||
Cycle(engine, Liquid)
|
|
||||||
Decrement(engine, Liquid)
|
|
||||||
For(engine, Liquid)
|
|
||||||
If(engine, Liquid)
|
|
||||||
Include(engine, Liquid)
|
|
||||||
Increment(engine, Liquid)
|
|
||||||
Layout(engine, Liquid)
|
|
||||||
Raw(engine, Liquid)
|
|
||||||
Tablerow(engine, Liquid)
|
|
||||||
Unless(engine, Liquid)
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
import assert from '../util/assert'
|
|
||||||
import { value as rValue } from '../lexical'
|
|
||||||
|
|
||||||
/*
|
|
||||||
* blockMode:
|
|
||||||
* * "store": store rendered html into blocks
|
|
||||||
* * "output": output rendered html
|
|
||||||
*/
|
|
||||||
|
|
||||||
export default function (liquid, Liquid) {
|
|
||||||
const staticFileRE = /\S+/
|
|
||||||
|
|
||||||
liquid.registerTag('layout', {
|
|
||||||
parse: function (token, remainTokens) {
|
|
||||||
let match = staticFileRE.exec(token.args)
|
|
||||||
if (match) {
|
|
||||||
this.staticLayout = match[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
match = rValue.exec(token.args)
|
|
||||||
if (match) {
|
|
||||||
this.layout = match[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
this.tpls = liquid.parser.parse(remainTokens)
|
|
||||||
},
|
|
||||||
render: async function (scope, hash) {
|
|
||||||
const layout = scope.opts.dynamicPartials
|
|
||||||
? Liquid.evalValue(this.layout, scope)
|
|
||||||
: this.staticLayout
|
|
||||||
assert(layout, `cannot apply layout with empty filename`)
|
|
||||||
|
|
||||||
// render the remaining tokens immediately
|
|
||||||
scope.opts.blockMode = 'store'
|
|
||||||
const html = await liquid.renderer.renderTemplates(this.tpls, scope)
|
|
||||||
if (scope.opts.blocks[''] === undefined) {
|
|
||||||
scope.opts.blocks[''] = html
|
|
||||||
}
|
|
||||||
const templates = await liquid.getTemplate(layout, scope.opts.root)
|
|
||||||
scope.push(hash)
|
|
||||||
scope.opts.blockMode = 'output'
|
|
||||||
const partial = await liquid.renderer.renderTemplates(templates, scope)
|
|
||||||
scope.pop(hash)
|
|
||||||
return partial
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
liquid.registerTag('block', {
|
|
||||||
parse: function (token, remainTokens) {
|
|
||||||
const match = /\w+/.exec(token.args)
|
|
||||||
this.block = match ? match[0] : ''
|
|
||||||
|
|
||||||
this.tpls = []
|
|
||||||
const stream = liquid.parser.parseStream(remainTokens)
|
|
||||||
.on('tag:endblock', () => stream.stop())
|
|
||||||
.on('template', tpl => this.tpls.push(tpl))
|
|
||||||
.on('end', () => {
|
|
||||||
throw new Error(`tag ${token.raw} not closed`)
|
|
||||||
})
|
|
||||||
stream.start()
|
|
||||||
},
|
|
||||||
render: async function (scope) {
|
|
||||||
const childDefined = scope.opts.blocks[this.block]
|
|
||||||
const html = childDefined !== undefined
|
|
||||||
? childDefined
|
|
||||||
: await liquid.renderer.renderTemplates(this.tpls, scope)
|
|
||||||
|
|
||||||
if (scope.opts.blockMode === 'store') {
|
|
||||||
scope.opts.blocks[this.block] = html
|
|
||||||
return ''
|
|
||||||
}
|
|
||||||
return html
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
export default function (liquid) {
|
|
||||||
liquid.registerTag('raw', {
|
|
||||||
parse: function (tagToken, remainTokens) {
|
|
||||||
this.tokens = []
|
|
||||||
|
|
||||||
const stream = liquid.parser.parseStream(remainTokens)
|
|
||||||
stream
|
|
||||||
.on('token', token => {
|
|
||||||
if (token.name === 'endraw') stream.stop()
|
|
||||||
else this.tokens.push(token)
|
|
||||||
})
|
|
||||||
.on('end', () => {
|
|
||||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
|
||||||
})
|
|
||||||
stream.start()
|
|
||||||
},
|
|
||||||
render: function (scope, hash) {
|
|
||||||
return this.tokens.map(token => token.raw).join('')
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
import { mapSeries } from '../util/promise'
|
|
||||||
import assert from '../util/assert'
|
|
||||||
import { identifier, value, hash } from '../lexical'
|
|
||||||
|
|
||||||
export default function (liquid, Liquid) {
|
|
||||||
const re = new RegExp(`^(${identifier.source})\\s+in\\s+` +
|
|
||||||
`(${value.source})` +
|
|
||||||
`(?:\\s+${hash.source})*$`)
|
|
||||||
|
|
||||||
liquid.registerTag('tablerow', {
|
|
||||||
|
|
||||||
parse: function (tagToken, remainTokens) {
|
|
||||||
const match = re.exec(tagToken.args)
|
|
||||||
assert(match, `illegal tag: ${tagToken.raw}`)
|
|
||||||
|
|
||||||
this.variable = match[1]
|
|
||||||
this.collection = match[2]
|
|
||||||
this.templates = []
|
|
||||||
|
|
||||||
let p
|
|
||||||
const stream = liquid.parser.parseStream(remainTokens)
|
|
||||||
.on('start', () => (p = this.templates))
|
|
||||||
.on('tag:endtablerow', token => stream.stop())
|
|
||||||
.on('template', tpl => p.push(tpl))
|
|
||||||
.on('end', () => {
|
|
||||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
|
||||||
})
|
|
||||||
|
|
||||||
stream.start()
|
|
||||||
},
|
|
||||||
|
|
||||||
render: async function (scope, hash) {
|
|
||||||
let collection = Liquid.evalExp(this.collection, scope) || []
|
|
||||||
const offset = hash.offset || 0
|
|
||||||
const limit = (hash.limit === undefined) ? collection.length : hash.limit
|
|
||||||
|
|
||||||
collection = collection.slice(offset, offset + limit)
|
|
||||||
const cols = hash.cols || collection.length
|
|
||||||
const contexts = collection.map((item, i) => {
|
|
||||||
const ctx = {}
|
|
||||||
ctx[this.variable] = item
|
|
||||||
return ctx
|
|
||||||
})
|
|
||||||
|
|
||||||
let row
|
|
||||||
let html = ''
|
|
||||||
await mapSeries(contexts, async (context, idx) => {
|
|
||||||
row = Math.floor(idx / cols) + 1
|
|
||||||
const col = (idx % cols) + 1
|
|
||||||
if (col === 1) {
|
|
||||||
if (row !== 1) {
|
|
||||||
html += '</tr>'
|
|
||||||
}
|
|
||||||
html += `<tr class="row${row}">`
|
|
||||||
}
|
|
||||||
|
|
||||||
html += `<td class="col${col}">`
|
|
||||||
scope.push(context)
|
|
||||||
html += await liquid.renderer.renderTemplates(this.templates, scope)
|
|
||||||
html += '</td>'
|
|
||||||
scope.pop(context)
|
|
||||||
return html
|
|
||||||
})
|
|
||||||
if (row > 0) {
|
|
||||||
html += '</tr>'
|
|
||||||
}
|
|
||||||
return html
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
export default function (liquid, Liquid) {
|
|
||||||
liquid.registerTag('unless', {
|
|
||||||
parse: function (tagToken, remainTokens) {
|
|
||||||
this.templates = []
|
|
||||||
this.elseTemplates = []
|
|
||||||
let p
|
|
||||||
const stream = liquid.parser.parseStream(remainTokens)
|
|
||||||
.on('start', x => {
|
|
||||||
p = this.templates
|
|
||||||
this.cond = tagToken.args
|
|
||||||
})
|
|
||||||
.on('tag:else', () => (p = this.elseTemplates))
|
|
||||||
.on('tag:endunless', token => stream.stop())
|
|
||||||
.on('template', tpl => p.push(tpl))
|
|
||||||
.on('end', x => {
|
|
||||||
throw new Error(`tag ${tagToken.raw} not closed`)
|
|
||||||
})
|
|
||||||
|
|
||||||
stream.start()
|
|
||||||
},
|
|
||||||
|
|
||||||
render: function (scope, hash) {
|
|
||||||
const cond = Liquid.evalExp(this.cond, scope)
|
|
||||||
return Liquid.isFalsy(cond)
|
|
||||||
? liquid.renderer.renderTemplates(this.templates, scope)
|
|
||||||
: liquid.renderer.renderTemplates(this.elseTemplates, scope)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import assert from 'src/util/assert'
|
||||||
|
import * as lexical from 'src/parser/lexical'
|
||||||
|
import { evalValue } from 'src/render/syntax'
|
||||||
|
import Scope from 'src/scope/scope'
|
||||||
|
|
||||||
|
type impl = (value: any, ...args: any[]) => any
|
||||||
|
|
||||||
|
const valueRE = new RegExp(`${lexical.value.source}`, 'g')
|
||||||
|
|
||||||
|
export default class Filter {
|
||||||
|
name: string
|
||||||
|
impl: impl
|
||||||
|
args: string[]
|
||||||
|
private static impls: {[key: string]: impl} = {}
|
||||||
|
|
||||||
|
constructor (str: string, strict_filters: boolean = false) {
|
||||||
|
let match = lexical.filterLine.exec(str)
|
||||||
|
assert(match, 'illegal filter: ' + str)
|
||||||
|
|
||||||
|
const name = match[1]
|
||||||
|
const argList = match[2] || ''
|
||||||
|
const impl = Filter.impls[name]
|
||||||
|
if (!impl && strict_filters) throw new TypeError(`undefined filter: ${name}`)
|
||||||
|
|
||||||
|
this.name = name
|
||||||
|
this.impl = impl || (x => x)
|
||||||
|
this.args = this.parseArgs(argList)
|
||||||
|
}
|
||||||
|
parseArgs (argList: string): string[] {
|
||||||
|
let match, args = []
|
||||||
|
while ((match = valueRE.exec(argList.trim()))) {
|
||||||
|
const v = match[0]
|
||||||
|
const re = new RegExp(`${v}\\s*:`, 'g')
|
||||||
|
const keyMatch = re.exec(match.input)
|
||||||
|
const currentMatchIsKey = keyMatch && keyMatch.index === match.index
|
||||||
|
currentMatchIsKey ? args.push(`'${v}'`) : args.push(v)
|
||||||
|
}
|
||||||
|
return args
|
||||||
|
}
|
||||||
|
render (value: any, scope: Scope): any {
|
||||||
|
const args = this.args.map(arg => evalValue(arg, scope))
|
||||||
|
args.unshift(value)
|
||||||
|
return this.impl.apply(null, args)
|
||||||
|
}
|
||||||
|
static register(name, filter) {
|
||||||
|
Filter.impls[name] = filter
|
||||||
|
}
|
||||||
|
static clear () {
|
||||||
|
Filter.impls = {}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import Template from 'src/template/template'
|
||||||
|
import Scope from 'src/scope/scope'
|
||||||
|
import ITemplate from 'src/template/itemplate'
|
||||||
|
import Token from 'src/parser/token'
|
||||||
|
|
||||||
|
export default class extends Template implements ITemplate {
|
||||||
|
str: string
|
||||||
|
constructor(token: Token) {
|
||||||
|
super(token)
|
||||||
|
this.str = token.value
|
||||||
|
}
|
||||||
|
async render(scope: Scope): Promise<string> {
|
||||||
|
return this.str
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import Scope from 'src/scope/scope'
|
||||||
|
import Token from 'src/parser/token'
|
||||||
|
|
||||||
|
export default interface ITemplate {
|
||||||
|
token: Token;
|
||||||
|
render(scope: Scope): Promise<string>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import Value from './value'
|
||||||
|
import { stringify } from 'src/util/underscore'
|
||||||
|
import Template from 'src/template/template'
|
||||||
|
import ITemplate from 'src/template/itemplate'
|
||||||
|
import Scope from 'src/scope/scope'
|
||||||
|
|
||||||
|
export default class Output extends Template implements ITemplate {
|
||||||
|
value: Value
|
||||||
|
constructor(token, strict_filters?) {
|
||||||
|
super(token)
|
||||||
|
this.value = new Value(token.value, strict_filters)
|
||||||
|
}
|
||||||
|
async render(scope: Scope) {
|
||||||
|
const html = await this.value.value(scope)
|
||||||
|
return stringify(html)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { hashCapture } from 'src/parser/lexical'
|
||||||
|
import { evalValue } from 'src/render/syntax'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Key-Value Pairs Representing Tag Arguments
|
||||||
|
* Example:
|
||||||
|
* For the markup `{% include 'head.html' foo='bar' %}`,
|
||||||
|
* hash['foo'] === 'bar'
|
||||||
|
*/
|
||||||
|
export default class Hash {
|
||||||
|
constructor(markup, scope) {
|
||||||
|
let match
|
||||||
|
hashCapture.lastIndex = 0
|
||||||
|
while ((match = hashCapture.exec(markup))) {
|
||||||
|
const k = match[1]
|
||||||
|
const v = match[2]
|
||||||
|
this[k] = evalValue(v, scope)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { create } from 'src/util/underscore'
|
||||||
|
import { stringify } from 'src/util/underscore'
|
||||||
|
import assert from 'src/util/assert'
|
||||||
|
import TagImpl from './tagimpl'
|
||||||
|
import Hash from './hash'
|
||||||
|
import Template from 'src/template/template'
|
||||||
|
import ITemplate from 'src/template/itemplate'
|
||||||
|
import TagToken from 'src/parser/tag-token'
|
||||||
|
|
||||||
|
export default class Tag extends Template implements ITemplate {
|
||||||
|
name: string
|
||||||
|
token: TagToken
|
||||||
|
private impl: TagImpl
|
||||||
|
static impls: object = {}
|
||||||
|
|
||||||
|
constructor (token, tokens, liquid) {
|
||||||
|
super(token)
|
||||||
|
this.name = token.name
|
||||||
|
|
||||||
|
const impl = Tag.impls[token.name]
|
||||||
|
assert(impl, `tag ${token.name} not found`)
|
||||||
|
this.impl = create(impl)
|
||||||
|
this.impl.liquid = liquid
|
||||||
|
if (this.impl.parse) {
|
||||||
|
this.impl.parse(token, tokens)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async render (scope) {
|
||||||
|
const hash = new Hash(this.token.args, scope)
|
||||||
|
const impl = this.impl
|
||||||
|
if (typeof impl.render !== 'function') {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
const html = await impl.render(scope, hash)
|
||||||
|
return stringify(html)
|
||||||
|
}
|
||||||
|
static register (name, tag) {
|
||||||
|
Tag.impls[name] = tag
|
||||||
|
}
|
||||||
|
static clear () {
|
||||||
|
Tag.impls = {}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import Liquid from 'src/liquid'
|
||||||
|
import Scope from 'src/scope/scope'
|
||||||
|
|
||||||
|
export default interface TagImpl {
|
||||||
|
liquid: Liquid
|
||||||
|
parse: (token: any, remainingTokens: Array<any>) => void
|
||||||
|
render: (scope: Scope, hash: any) => Promise<string>
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import Token from 'src/parser/token'
|
||||||
|
|
||||||
|
export default class Template {
|
||||||
|
token: Token;
|
||||||
|
constructor(token) {
|
||||||
|
this.token = token;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { evalExp } from 'src/render/syntax'
|
||||||
|
import * as lexical from 'src/parser/lexical'
|
||||||
|
import assert from 'src/util/assert'
|
||||||
|
import Filter from './filter'
|
||||||
|
import Scope from 'src/scope/scope'
|
||||||
|
|
||||||
|
export default class {
|
||||||
|
initial: any
|
||||||
|
filters: Array<any>
|
||||||
|
constructor(str: string, strict_filters?: boolean) {
|
||||||
|
let match = lexical.matchValue(str)
|
||||||
|
assert(match, `illegal value string: ${str}`)
|
||||||
|
|
||||||
|
const initial = match[0]
|
||||||
|
str = str.substr(match.index + match[0].length)
|
||||||
|
|
||||||
|
const filters = []
|
||||||
|
while ((match = lexical.filter.exec(str))) {
|
||||||
|
filters.push([match[0].trim()])
|
||||||
|
}
|
||||||
|
|
||||||
|
this.initial = initial
|
||||||
|
this.filters = filters.map(str => new Filter(str, strict_filters))
|
||||||
|
}
|
||||||
|
value(scope: Scope) {
|
||||||
|
return this.filters.reduce(
|
||||||
|
(prev, filter) => filter.render(prev, scope),
|
||||||
|
evalExp(this.initial, scope))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
import * as lexical from './lexical'
|
|
||||||
import { TokenizationError } from './util/error'
|
|
||||||
import * as _ from './util/underscore'
|
|
||||||
import assert from './util/assert'
|
|
||||||
import whiteSpaceCtrl from './whitespace-ctrl'
|
|
||||||
|
|
||||||
export { default as whiteSpaceCtrl } from './whitespace-ctrl'
|
|
||||||
|
|
||||||
export function parse (input, file, options) {
|
|
||||||
assert(_.isString(input), 'illegal input')
|
|
||||||
|
|
||||||
const rLiquid = /({%-?([\s\S]*?)-?%})|({{-?([\s\S]*?)-?}})/g
|
|
||||||
let currIndent = 0
|
|
||||||
const lineNumber = LineNumber(input)
|
|
||||||
let lastMatchEnd = 0
|
|
||||||
const tokens = []
|
|
||||||
|
|
||||||
for (let match; (match = rLiquid.exec(input)); lastMatchEnd = rLiquid.lastIndex) {
|
|
||||||
if (match.index > lastMatchEnd) {
|
|
||||||
tokens.push(parseHTMLToken(lastMatchEnd, match.index))
|
|
||||||
}
|
|
||||||
tokens.push(match[1]
|
|
||||||
? parseTagToken(match[1], match[2].trim(), match.index)
|
|
||||||
: parseValueToken(match[3], match[4].trim(), match.index))
|
|
||||||
}
|
|
||||||
if (input.length > lastMatchEnd) {
|
|
||||||
tokens.push(parseHTMLToken(lastMatchEnd, input.length))
|
|
||||||
}
|
|
||||||
whiteSpaceCtrl(tokens, options)
|
|
||||||
return tokens
|
|
||||||
|
|
||||||
function parseTagToken (raw, value, pos) {
|
|
||||||
const match = value.match(lexical.tagLine)
|
|
||||||
const token = {
|
|
||||||
type: 'tag',
|
|
||||||
indent: currIndent,
|
|
||||||
line: lineNumber.get(pos),
|
|
||||||
trim_left: raw.slice(0, 3) === '{%-',
|
|
||||||
trim_right: raw.slice(-3) === '-%}',
|
|
||||||
raw,
|
|
||||||
value,
|
|
||||||
input,
|
|
||||||
file
|
|
||||||
}
|
|
||||||
if (!match) {
|
|
||||||
throw new TokenizationError(`illegal tag syntax`, token)
|
|
||||||
}
|
|
||||||
token.name = match[1]
|
|
||||||
token.args = match[2]
|
|
||||||
return token
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseValueToken (raw, value, pos) {
|
|
||||||
return {
|
|
||||||
type: 'value',
|
|
||||||
line: lineNumber.get(pos),
|
|
||||||
trim_left: raw.slice(0, 3) === '{{-',
|
|
||||||
trim_right: raw.slice(-3) === '-}}',
|
|
||||||
raw,
|
|
||||||
value,
|
|
||||||
input,
|
|
||||||
file
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseHTMLToken (begin, end) {
|
|
||||||
const htmlFragment = input.slice(begin, end)
|
|
||||||
currIndent = _.last((htmlFragment).split('\n')).length
|
|
||||||
|
|
||||||
return {
|
|
||||||
type: 'html',
|
|
||||||
raw: htmlFragment,
|
|
||||||
value: htmlFragment
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function LineNumber (html) {
|
|
||||||
let parsedLinesCount = 0
|
|
||||||
let lastMatchBegin = -1
|
|
||||||
|
|
||||||
return {
|
|
||||||
get: function (pos) {
|
|
||||||
const lines = html.slice(lastMatchBegin + 1, pos).split('\n')
|
|
||||||
parsedLinesCount += lines.length - 1
|
|
||||||
lastMatchBegin = pos
|
|
||||||
return parsedLinesCount + 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export { AssignScope, CaptureScope, IncrementScope, DecrementScope } from './scope/scopes'
|
||||||
|
export { ParseError, TokenizationError, RenderBreakError, AssertionError } from './util/error'
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
import { AssertionError } from './error'
|
import { AssertionError } from './error'
|
||||||
|
|
||||||
export default function (predicate: any, message: string) {
|
export default function (predicate: any, message?: string) {
|
||||||
if (!predicate) {
|
if (!predicate) {
|
||||||
message = message || `expect ${predicate} to be true`
|
message = message || `expect ${predicate} to be true`
|
||||||
throw new AssertionError(message)
|
throw new AssertionError(message)
|
||||||
|
|||||||
+5
-9
@@ -1,4 +1,5 @@
|
|||||||
import * as _ from './underscore'
|
import * as _ from './underscore'
|
||||||
|
import Token from 'src/parser/token'
|
||||||
|
|
||||||
function captureStack () {
|
function captureStack () {
|
||||||
if (Error.captureStackTrace) {
|
if (Error.captureStackTrace) {
|
||||||
@@ -13,8 +14,8 @@ abstract class LiquidError {
|
|||||||
message: string
|
message: string
|
||||||
name: string
|
name: string
|
||||||
stack: string
|
stack: string
|
||||||
token: any
|
token: Token
|
||||||
originalError: any
|
originalError: Error
|
||||||
constructor(err, token) {
|
constructor(err, token) {
|
||||||
this.input = token.input
|
this.input = token.input
|
||||||
this.line = token.line
|
this.line = token.line
|
||||||
@@ -66,6 +67,7 @@ RenderError.prototype.constructor = RenderError
|
|||||||
|
|
||||||
export class RenderBreakError {
|
export class RenderBreakError {
|
||||||
message: string
|
message: string
|
||||||
|
resolvedHTML: string
|
||||||
constructor (message) {
|
constructor (message) {
|
||||||
captureStack.call(this)
|
captureStack.call(this)
|
||||||
this.message = message + ''
|
this.message = message + ''
|
||||||
@@ -93,7 +95,7 @@ function mkContext (input, targetLine) {
|
|||||||
.range(begin, end + 1)
|
.range(begin, end + 1)
|
||||||
.map(lineNumber => {
|
.map(lineNumber => {
|
||||||
const indicator = (lineNumber === targetLine) ? '>> ' : ' '
|
const indicator = (lineNumber === targetLine) ? '>> ' : ' '
|
||||||
const num = padStart(String(end).length, lineNumber)
|
const num = _.padStart(String(lineNumber), String(end).length)
|
||||||
const text = lines[lineNumber - 1]
|
const text = lines[lineNumber - 1]
|
||||||
return `${indicator}${num}| ${text}`
|
return `${indicator}${num}| ${text}`
|
||||||
})
|
})
|
||||||
@@ -112,9 +114,3 @@ function mkMessage (msg, token) {
|
|||||||
}
|
}
|
||||||
return msg
|
return msg
|
||||||
}
|
}
|
||||||
|
|
||||||
function padStart (length, str) {
|
|
||||||
str = String(str)
|
|
||||||
const blank = Array(length - str.length).join(' ')
|
|
||||||
return blank + str
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/*
|
/*
|
||||||
* Call functions in serial until someone resolved.
|
* Call functions in serial until someone resolved.
|
||||||
* @param {Array} iterable the array to iterate with.
|
* @param iterable the array to iterate with.
|
||||||
* @param {Array} iteratee returns a new promise.
|
* @param iteratee returns a new promise.
|
||||||
* The iteratee is invoked with three arguments: (value, index, iterable).
|
* The iteratee is invoked with three arguments: (value, index, iterable).
|
||||||
*/
|
*/
|
||||||
export function anySeries (iterable, iteratee) {
|
export function anySeries (iterable, iteratee) {
|
||||||
let ret = Promise.reject(new Error('init'))
|
let ret: Promise<any> = Promise.reject(new Error('init'))
|
||||||
iterable.forEach(function (item, idx) {
|
iterable.forEach(function (item, idx) {
|
||||||
ret = ret.catch(e => iteratee(item, idx, iterable))
|
ret = ret.catch(e => iteratee(item, idx, iterable))
|
||||||
})
|
})
|
||||||
@@ -19,7 +19,7 @@ export function anySeries (iterable, iteratee) {
|
|||||||
* The iteratee is invoked with three arguments: (value, index, iterable).
|
* The iteratee is invoked with three arguments: (value, index, iterable).
|
||||||
*/
|
*/
|
||||||
export function mapSeries (iterable, iteratee) {
|
export function mapSeries (iterable, iteratee) {
|
||||||
let ret = Promise.resolve('init')
|
let ret: Promise<any> = Promise.resolve('init')
|
||||||
const result = []
|
const result = []
|
||||||
iterable.forEach(function (item, idx) {
|
iterable.forEach(function (item, idx) {
|
||||||
ret = ret
|
ret = ret
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { padStart } from './underscore'
|
||||||
|
|
||||||
const monthNames = [
|
const monthNames = [
|
||||||
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
|
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
|
||||||
'September', 'October', 'November', 'December'
|
'September', 'October', 'November', 'December'
|
||||||
@@ -41,7 +43,7 @@ const _date = {
|
|||||||
// Find the first startDay of the year
|
// Find the first startDay of the year
|
||||||
const jan1 = new Date(d.getFullYear(), 0, 1)
|
const jan1 = new Date(d.getFullYear(), 0, 1)
|
||||||
const then = (7 - jan1.getDay() + startDay)
|
const then = (7 - jan1.getDay() + startDay)
|
||||||
return _number.pad(Math.floor((now - then) / 7) + 1, 2)
|
return padStart(String(Math.floor((now - then) / 7) + 1), 2, '0')
|
||||||
},
|
},
|
||||||
|
|
||||||
isLeapYear: function (d) {
|
isLeapYear: function (d) {
|
||||||
@@ -60,20 +62,6 @@ const _date = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const _number = {
|
|
||||||
pad: function (value, size, ch) {
|
|
||||||
if (!ch) ch = '0'
|
|
||||||
let result = value.toString()
|
|
||||||
let pad = size - result.length
|
|
||||||
|
|
||||||
while (pad-- > 0) {
|
|
||||||
result = ch + result
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const formatCodes = {
|
const formatCodes = {
|
||||||
a: function (d) {
|
a: function (d) {
|
||||||
return dayNamesShort[d.getDay()]
|
return dayNamesShort[d.getDay()]
|
||||||
@@ -94,34 +82,34 @@ const formatCodes = {
|
|||||||
return _date.century(d)
|
return _date.century(d)
|
||||||
},
|
},
|
||||||
d: function (d) {
|
d: function (d) {
|
||||||
return _number.pad(d.getDate(), 2)
|
return padStart(d.getDate(), 2, '0')
|
||||||
},
|
},
|
||||||
e: function (d) {
|
e: function (d) {
|
||||||
return _number.pad(d.getDate(), 2, ' ')
|
return padStart(d.getDate(), 2)
|
||||||
},
|
},
|
||||||
H: function (d) {
|
H: function (d) {
|
||||||
return _number.pad(d.getHours(), 2)
|
return padStart(d.getHours(), 2, '0')
|
||||||
},
|
},
|
||||||
I: function (d) {
|
I: function (d) {
|
||||||
return _number.pad(d.getHours() % 12 || 12, 2)
|
return padStart(String(d.getHours() % 12 || 12), 2, '0')
|
||||||
},
|
},
|
||||||
j: function (d) {
|
j: function (d) {
|
||||||
return _number.pad(_date.getDayOfYear(d), 3)
|
return padStart(_date.getDayOfYear(d), 3, '0')
|
||||||
},
|
},
|
||||||
k: function (d) {
|
k: function (d) {
|
||||||
return _number.pad(d.getHours(), 2, ' ')
|
return padStart(d.getHours(), 2)
|
||||||
},
|
},
|
||||||
l: function (d) {
|
l: function (d) {
|
||||||
return _number.pad(d.getHours() % 12 || 12, 2, ' ')
|
return padStart(String(d.getHours() % 12 || 12), 2)
|
||||||
},
|
},
|
||||||
L: function (d) {
|
L: function (d) {
|
||||||
return _number.pad(d.getMilliseconds(), 3)
|
return padStart(d.getMilliseconds(), 3, '0')
|
||||||
},
|
},
|
||||||
m: function (d) {
|
m: function (d) {
|
||||||
return _number.pad(d.getMonth() + 1, 2)
|
return padStart(d.getMonth() + 1, 2, '0')
|
||||||
},
|
},
|
||||||
M: function (d) {
|
M: function (d) {
|
||||||
return _number.pad(d.getMinutes(), 2)
|
return padStart(d.getMinutes(), 2, '0')
|
||||||
},
|
},
|
||||||
p: function (d) {
|
p: function (d) {
|
||||||
return (d.getHours() < 12 ? 'AM' : 'PM')
|
return (d.getHours() < 12 ? 'AM' : 'PM')
|
||||||
@@ -136,7 +124,7 @@ const formatCodes = {
|
|||||||
return Math.round(d.valueOf() / 1000)
|
return Math.round(d.valueOf() / 1000)
|
||||||
},
|
},
|
||||||
S: function (d) {
|
S: function (d) {
|
||||||
return _number.pad(d.getSeconds(), 2)
|
return padStart(d.getSeconds(), 2, '0')
|
||||||
},
|
},
|
||||||
u: function (d) {
|
u: function (d) {
|
||||||
return d.getDay() || 7
|
return d.getDay() || 7
|
||||||
@@ -164,14 +152,14 @@ const formatCodes = {
|
|||||||
},
|
},
|
||||||
z: function (d) {
|
z: function (d) {
|
||||||
const tz = d.getTimezoneOffset() / 60 * 100
|
const tz = d.getTimezoneOffset() / 60 * 100
|
||||||
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4)
|
return (tz > 0 ? '-' : '+') + padStart(String(Math.abs(tz)), 4, '0')
|
||||||
},
|
},
|
||||||
'%': function () {
|
'%': function () {
|
||||||
return '%'
|
return '%'
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
formatCodes.h = formatCodes.b
|
(formatCodes as any).h = formatCodes.b;
|
||||||
formatCodes.N = formatCodes.L
|
(formatCodes as any).N = formatCodes.L;
|
||||||
|
|
||||||
export default function (d, format) {
|
export default function (d, format) {
|
||||||
let output = ''
|
let output = ''
|
||||||
@@ -25,7 +25,7 @@ export function promisify (fn) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function stringify (value) {
|
export function stringify (value) {
|
||||||
if (isNil(value)) return String(value)
|
if (isNil(value)) return ''
|
||||||
if (isFunction(value.to_liquid)) return stringify(value.to_liquid())
|
if (isFunction(value.to_liquid)) return stringify(value.to_liquid())
|
||||||
if (isFunction(value.toLiquid)) return stringify(value.toLiquid())
|
if (isFunction(value.toLiquid)) return stringify(value.toLiquid())
|
||||||
if (isFunction(value.to_s)) return value.to_s()
|
if (isFunction(value.to_s)) return value.to_s()
|
||||||
@@ -142,7 +142,7 @@ export function isObject (value) {
|
|||||||
* Note that ranges that stop before they start are considered to be zero-length instead of
|
* Note that ranges that stop before they start are considered to be zero-length instead of
|
||||||
* negative — if you'd like a negative range, use a negative step.
|
* negative — if you'd like a negative range, use a negative step.
|
||||||
*/
|
*/
|
||||||
export function range (start: number, stop: number, step?: number) {
|
export function range (start: number, stop?: number, step?: number) {
|
||||||
if (arguments.length === 1) {
|
if (arguments.length === 1) {
|
||||||
stop = start
|
stop = start
|
||||||
start = 0
|
start = 0
|
||||||
@@ -155,3 +155,10 @@ export function range (start: number, stop: number, step?: number) {
|
|||||||
}
|
}
|
||||||
return arr
|
return arr
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function padStart(str: any, length: number, ch: string = ' ') {
|
||||||
|
str = String(str)
|
||||||
|
let n = length - str.length
|
||||||
|
while(n-- > 0) str = ch + str
|
||||||
|
return str
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
{
|
|
||||||
"rules": {
|
|
||||||
"no-unused-expressions": "off"
|
|
||||||
},
|
|
||||||
"env": {
|
|
||||||
"mocha": true
|
|
||||||
},
|
|
||||||
"plugins": [
|
|
||||||
"mocha"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
var chai = require('chai')
|
||||||
|
var Liquid = require('../..')
|
||||||
|
var expect = chai.expect
|
||||||
|
|
||||||
|
chai.use(require('chai-as-promised'))
|
||||||
|
|
||||||
|
describe('.evalValue()', function () {
|
||||||
|
var engine
|
||||||
|
beforeEach(() => engine = new Liquid())
|
||||||
|
|
||||||
|
it('should throw when scope undefined', function () {
|
||||||
|
expect(() => engine.evalValue('{{"foo"}}')).to.throw(/scope undefined/)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
const chai = require('chai')
|
import * as chai from 'chai'
|
||||||
const request = require('supertest')
|
import * as request from 'supertest'
|
||||||
const express = require('express')
|
import * as express from 'express'
|
||||||
const mock = require('mock-fs')
|
import * as mock from 'mock-fs'
|
||||||
const Liquid = require('../../dist/liquid.common.js')
|
import Liquid from '../../dist/liquid.common.js'
|
||||||
const chaiAsPromised = require('chai-as-promised')
|
import * as chaiAsPromised from 'chai-as-promised'
|
||||||
|
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
chai.use(chaiAsPromised)
|
chai.use(chaiAsPromised)
|
||||||
|
|
||||||
describe('engine#express()', function () {
|
describe('express()', function () {
|
||||||
var app, engine
|
var app, engine
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
@@ -84,7 +84,7 @@ describe('engine#express()', function () {
|
|||||||
.expect('bar')
|
.expect('bar')
|
||||||
.expect(200, done)
|
.expect(200, done)
|
||||||
})
|
})
|
||||||
it('should respect express views (Undefined) when lookup', function (done) {
|
it('should respect express views (undefined) when lookup', function (done) {
|
||||||
const files = {}
|
const files = {}
|
||||||
files[process.cwd() + '/views/include.html'] = '{% include file %}'
|
files[process.cwd() + '/views/include.html'] = '{% include file %}'
|
||||||
files[process.cwd() + '/views/bar.html'] = 'bar'
|
files[process.cwd() + '/views/bar.html'] = 'bar'
|
||||||
@@ -12,15 +12,15 @@ describe('.parseAndRender()', function () {
|
|||||||
strict_filters: true
|
strict_filters: true
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
it('should value object', function () {
|
it('should stringify object', function () {
|
||||||
var ctx = { obj: { foo: 'bar' } }
|
var ctx = { obj: { foo: 'bar' } }
|
||||||
return expect(engine.parseAndRender('{{obj}}', ctx)).to.eventually.equal('{"foo":"bar"}')
|
return expect(engine.parseAndRender('{{obj}}', ctx)).to.eventually.equal('{"foo":"bar"}')
|
||||||
})
|
})
|
||||||
it('should value array', function () {
|
it('should stringify array ', function () {
|
||||||
var ctx = { arr: [-2, 'a'] }
|
var ctx = { arr: [-2, 'a'] }
|
||||||
return expect(engine.parseAndRender('{{arr}}', ctx)).to.eventually.equal('[-2,"a"]')
|
return expect(engine.parseAndRender('{{arr}}', ctx)).to.eventually.equal('[-2,"a"]')
|
||||||
})
|
})
|
||||||
it('should value undefined to empty', function () {
|
it('should render undefined as empty', function () {
|
||||||
return expect(engine.parseAndRender('foo{{zzz}}bar', {})).to.eventually.equal('foobar')
|
return expect(engine.parseAndRender('foo{{zzz}}bar', {})).to.eventually.equal('foobar')
|
||||||
})
|
})
|
||||||
it('should render as null when filter undefined', function () {
|
it('should render as null when filter undefined', function () {
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
const chai = require('chai')
|
import * as chai from 'chai'
|
||||||
const Liquid = require('../..')
|
import Liquid from '../..'
|
||||||
|
import * as chaiAsPromised from 'chai-as-promised'
|
||||||
|
|
||||||
const liquid = new Liquid()
|
const liquid = new Liquid()
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
chai.use(require('chai-as-promised'))
|
chai.use(chaiAsPromised)
|
||||||
|
|
||||||
const cases = [
|
const cases = [
|
||||||
{
|
{
|
||||||
@@ -1,28 +1,30 @@
|
|||||||
var Liquid = require('../../dist/liquid.js')
|
import Liquid from '../../dist/liquid.js'
|
||||||
var sinon = require('sinon')
|
import { createFakeServer, useFakeXMLHttpRequest } from 'sinon'
|
||||||
var chai = require('chai')
|
import * as chai from 'chai'
|
||||||
var expect = chai.expect
|
import * as chaiAsPromised from 'chai-as-promised'
|
||||||
chai.use(require('chai-as-promised'))
|
import { JSDOM } from 'jsdom'
|
||||||
|
|
||||||
|
const expect = chai.expect
|
||||||
|
chai.use(chaiAsPromised)
|
||||||
|
|
||||||
describe('xhr', () => {
|
describe('xhr', () => {
|
||||||
if (process.version.match(/^v(\d+)/)[1] < 8) {
|
if (+process.version.match(/^v(\d+)/)[1] < 8) {
|
||||||
console.info('jsdom not supported, skipping xhr...')
|
console.info('jsdom not supported, skipping xhr...')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var JSDOM = require('jsdom').JSDOM
|
let server, engine
|
||||||
var server, engine
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
server = sinon.createFakeServer()
|
server = createFakeServer()
|
||||||
server.autoRespond = true
|
server.autoRespond = true
|
||||||
server.respondWith('GET', 'https://example.com/views/hello.html',
|
server.respondWith('GET', 'https://example.com/views/hello.html',
|
||||||
[200, { 'Content-Type': 'text/plain' }, 'hello {{name}}'])
|
[200, { 'Content-Type': 'text/plain' }, 'hello {{name}}'])
|
||||||
var dom = new JSDOM('', {
|
let dom = new JSDOM('', {
|
||||||
url: 'https://example.com/foo/bar.html',
|
url: 'https://example.com/foo/bar.html',
|
||||||
contentType: 'text/html',
|
contentType: 'text/html',
|
||||||
includeNodeLocations: true
|
includeNodeLocations: true
|
||||||
})
|
});
|
||||||
global.XMLHttpRequest = sinon.useFakeXMLHttpRequest()
|
(global as any).XMLHttpRequest = useFakeXMLHttpRequest();
|
||||||
global.document = dom.window.document
|
(global as any).document = dom.window.document;
|
||||||
engine = new Liquid({
|
engine = new Liquid({
|
||||||
root: 'https://example.com/views/',
|
root: 'https://example.com/views/',
|
||||||
extname: '.html'
|
extname: '.html'
|
||||||
@@ -30,8 +32,8 @@ describe('xhr', () => {
|
|||||||
})
|
})
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
server.restore()
|
server.restore()
|
||||||
delete global.XMLHttpRequest
|
delete (global as any).XMLHttpRequest
|
||||||
delete global.document
|
delete (global as any).document
|
||||||
})
|
})
|
||||||
describe('#renderFile()', () => {
|
describe('#renderFile()', () => {
|
||||||
it('should support without extname', () => {
|
it('should support without extname', () => {
|
||||||
@@ -70,8 +72,8 @@ describe('xhr', () => {
|
|||||||
.catch(function (e) {
|
.catch(function (e) {
|
||||||
expect(e.message).to.equal('An error occurred whilst receiving the response.')
|
expect(e.message).to.equal('An error occurred whilst receiving the response.')
|
||||||
done()
|
done()
|
||||||
})
|
});
|
||||||
global.XMLHttpRequest.onCreate = function (request) {
|
(global as any).XMLHttpRequest.onCreate = function (request) {
|
||||||
setTimeout(() => request.error())
|
setTimeout(() => request.error())
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
--require ts-node/register
|
|
||||||
--recursive
|
|
||||||
+27
-28
@@ -1,96 +1,95 @@
|
|||||||
import * as chai from 'chai'
|
import * as chai from 'chai'
|
||||||
import * as sinon from 'sinon'
|
import * as sinon from 'sinon'
|
||||||
import * as sinonChai from 'sinon-chai'
|
import * as sinonChai from 'sinon-chai'
|
||||||
import Filter from '../../src/filter'
|
import Filter from 'src/template/filter'
|
||||||
import { factory as scopeFactory } from '../../src/scope'
|
import Scope from 'src/scope/scope'
|
||||||
|
|
||||||
chai.use(sinonChai)
|
chai.use(sinonChai)
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
const filter = Filter()
|
|
||||||
|
|
||||||
describe('filter', function () {
|
describe('filter', function () {
|
||||||
let scope
|
let scope
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
filter.clear()
|
Filter.clear()
|
||||||
scope = scopeFactory()
|
scope = new Scope()
|
||||||
})
|
})
|
||||||
it('should return default filter when not registered', function () {
|
it('should return default filter when not registered', function () {
|
||||||
const result = filter.construct('foo')
|
const result = new Filter('foo')
|
||||||
expect(result.name).to.equal('foo')
|
expect(result.name).to.equal('foo')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should throw when filter name illegal', function () {
|
it('should throw when filter name illegal', function () {
|
||||||
expect(function () {
|
expect(function () {
|
||||||
filter.construct('/')
|
new Filter('/')
|
||||||
}).to.throw(/illegal filter/)
|
}).to.throw(/illegal filter/)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should parse argument syntax', function () {
|
it('should parse argument syntax', function () {
|
||||||
filter.register('foo', x => x)
|
Filter.register('foo', x => x)
|
||||||
const f = filter.construct('foo: a, "b"')
|
const f = new Filter('foo: a, "b"')
|
||||||
|
|
||||||
expect(f.name).to.equal('foo')
|
expect(f.name).to.equal('foo')
|
||||||
expect(f.args).to.deep.equal(['a', '"b"'])
|
expect(f.args).to.deep.equal(['a', '"b"'])
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should register a simple filter', function () {
|
it('should register a simple filter', function () {
|
||||||
filter.register('upcase', x => x.toUpperCase())
|
Filter.register('upcase', x => x.toUpperCase())
|
||||||
expect(filter.construct('upcase').render('foo', scope)).to.equal('FOO')
|
expect(new Filter('upcase').render('foo', scope)).to.equal('FOO')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should register a argumented filter', function () {
|
it('should register a argumented filter', function () {
|
||||||
filter.register('add', (a, b) => a + b)
|
Filter.register('add', (a, b) => a + b)
|
||||||
expect(filter.construct('add: 2').render(3, scope)).to.equal(5)
|
expect(new Filter('add: 2').render(3, scope)).to.equal(5)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should register a multi-argumented filter', function () {
|
it('should register a multi-argumented filter', function () {
|
||||||
filter.register('add', (a, b, c) => a + b + c)
|
Filter.register('add', (a, b, c) => a + b + c)
|
||||||
expect(filter.construct('add: 2, "c"').render(3, scope)).to.equal('5c')
|
expect(new Filter('add: 2, "c"').render(3, scope)).to.equal('5c')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should call filter with corrct arguments', function () {
|
it('should call filter with corrct arguments', function () {
|
||||||
const spy = sinon.spy()
|
const spy = sinon.spy()
|
||||||
filter.register('foo', spy)
|
Filter.register('foo', spy)
|
||||||
filter.construct('foo: 33').render('foo', scope)
|
new Filter('foo: 33').render('foo', scope)
|
||||||
expect(spy).to.have.been.calledWith('foo', 33)
|
expect(spy).to.have.been.calledWith('foo', 33)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should support arguments as named key/values', function () {
|
it('should support arguments as named key/values', function () {
|
||||||
filter.register('foo', x => x)
|
Filter.register('foo', x => x)
|
||||||
const f = filter.construct('foo: key1: "literal1", key2: value2')
|
const f = new Filter('foo: key1: "literal1", key2: value2')
|
||||||
expect(f.name).to.equal('foo')
|
expect(f.name).to.equal('foo')
|
||||||
expect(f.args).to.deep.equal([ '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
|
expect(f.args).to.deep.equal([ '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should support arguments as named key/values with inline literals', function () {
|
it('should support arguments as named key/values with inline literals', function () {
|
||||||
filter.register('foo', x => x)
|
Filter.register('foo', x => x)
|
||||||
const f = filter.construct('foo: "test0", key1: "literal1", key2: value2')
|
const f = new Filter('foo: "test0", key1: "literal1", key2: value2')
|
||||||
expect(f.name).to.equal('foo')
|
expect(f.name).to.equal('foo')
|
||||||
expect(f.args).to.deep.equal([ '"test0"', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
|
expect(f.args).to.deep.equal([ '"test0"', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should support arguments as named key/values with inline values', function () {
|
it('should support arguments as named key/values with inline values', function () {
|
||||||
filter.register('foo', x => x)
|
Filter.register('foo', x => x)
|
||||||
const f = filter.construct('foo: test0, key1: "literal1", key2: value2')
|
const f = new Filter('foo: test0, key1: "literal1", key2: value2')
|
||||||
expect(f.name).to.equal('foo')
|
expect(f.name).to.equal('foo')
|
||||||
expect(f.args).to.deep.equal([ 'test0', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
|
expect(f.args).to.deep.equal([ 'test0', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should support argument values named same as keys', function () {
|
it('should support argument values named same as keys', function () {
|
||||||
filter.register('foo', x => x)
|
Filter.register('foo', x => x)
|
||||||
const f = filter.construct('foo: a: a')
|
const f = new Filter('foo: a: a')
|
||||||
expect(f.name).to.equal('foo')
|
expect(f.name).to.equal('foo')
|
||||||
expect(f.args).to.deep.equal(['\'a\'', 'a'])
|
expect(f.args).to.deep.equal(['\'a\'', 'a'])
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should support argument literals named same as keys', function () {
|
it('should support argument literals named same as keys', function () {
|
||||||
filter.register('foo', x => x)
|
Filter.register('foo', x => x)
|
||||||
const f = filter.construct('foo: a: "a"')
|
const f = new Filter('foo: a: "a"')
|
||||||
expect(f.name).to.equal('foo')
|
expect(f.name).to.equal('foo')
|
||||||
expect(f.args).to.deep.equal(['\'a\'', '"a"'])
|
expect(f.args).to.deep.equal(['\'a\'', '"a"'])
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should not throw undefined filter by default', function () {
|
it('should not throw undefined filter by default', function () {
|
||||||
expect(filter.construct('undefined').render('foo', scope)).to.equal('foo')
|
expect(new Filter('undefined').render('foo', scope)).to.equal('foo')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import * as chai from 'chai'
|
import * as chai from 'chai'
|
||||||
import * as chaiAsPromised from 'chai-as-promised'
|
import * as chaiAsPromised from 'chai-as-promised'
|
||||||
import Liquid from '../../src/index'
|
import Liquid from '../../src/liquid'
|
||||||
|
|
||||||
chai.use(chaiAsPromised)
|
chai.use(chaiAsPromised)
|
||||||
const liquid = new Liquid()
|
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
|
|
||||||
const ctx = {
|
const ctx = {
|
||||||
@@ -20,12 +19,14 @@ const ctx = {
|
|||||||
category: 'bar'
|
category: 'bar'
|
||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
|
let liquid
|
||||||
|
|
||||||
function test (src, dst) {
|
function test (src, dst) {
|
||||||
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
|
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('filters', function () {
|
describe('filters', function () {
|
||||||
|
before(() => liquid = new Liquid())
|
||||||
describe('abs', function () {
|
describe('abs', function () {
|
||||||
it('should return 3 for -3', () => test('{{ -3 | abs }}', '3'))
|
it('should return 3 for -3', () => test('{{ -3 | abs }}', '3'))
|
||||||
it('should return 2 for arr[0]', () => test('{{ arr[0] | abs }}', '2'))
|
it('should return 2 for arr[0]', () => test('{{ arr[0] | abs }}', '2'))
|
||||||
@@ -416,8 +417,10 @@ describe('filters', function () {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('obj_test', function () {
|
describe('obj_test', function () {
|
||||||
liquid.registerFilter('obj_test', function () {
|
before(() => {
|
||||||
return Array.prototype.slice.call(arguments).join(',')
|
liquid.registerFilter('obj_test', function () {
|
||||||
|
return Array.prototype.slice.call(arguments).join(',')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
it('should support object', () => test(`{{ "a" | obj_test: k1: "v1", k2: foo }}`, 'a,k1,v1,k2,bar'))
|
it('should support object', () => test(`{{ "a" | obj_test: k1: "v1", k2: foo }}`, 'a,k1,v1,k2,bar'))
|
||||||
it('should support mixed object', () => test(`{{ "a" | obj_test: "something", k1: "v1", k2: foo }}`, 'a,something,k1,v1,k2,bar'))
|
it('should support mixed object', () => test(`{{ "a" | obj_test: "something", k1: "v1", k2: foo }}`, 'a,something,k1,v1,k2,bar'))
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
const chai = require('chai')
|
import * as chai from 'chai'
|
||||||
const expect = chai.expect
|
|
||||||
|
|
||||||
const lexical = require('../../src/lexical.js')
|
const expect = chai.expect
|
||||||
|
const lexical = require('../../src/parser/lexical')
|
||||||
|
|
||||||
describe('lexical', function () {
|
describe('lexical', function () {
|
||||||
it('should test filter syntax', function () {
|
it('should test filter syntax', function () {
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import Liquid from '../../src/index'
|
import Liquid from '../../src/liquid'
|
||||||
import * as mock from 'mock-fs'
|
import * as mock from 'mock-fs'
|
||||||
import * as chai from 'chai'
|
import * as chai from 'chai'
|
||||||
|
|
||||||
@@ -7,9 +7,7 @@ const expect = chai.expect
|
|||||||
describe('Liquid', function () {
|
describe('Liquid', function () {
|
||||||
describe('#constructor()', function () {
|
describe('#constructor()', function () {
|
||||||
it('should throw on illegal root', function () {
|
it('should throw on illegal root', function () {
|
||||||
expect(() => {
|
expect(() => new (Liquid as any)({root: {}})).to.throw(/illegal root/)
|
||||||
new Liquid({root: {}}) // eslint-disable-line
|
|
||||||
}).to.throw(/illegal root/)
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
describe('#plugin()', function () {
|
describe('#plugin()', function () {
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
import * as chai from 'chai'
|
import * as chai from 'chai'
|
||||||
import * as mock from 'mock-fs'
|
import * as mock from 'mock-fs'
|
||||||
import Liquid from '../../../src'
|
import Liquid from '../../../src/liquid'
|
||||||
import * as chaiAsPromised from 'chai-as-promised'
|
import * as chaiAsPromised from 'chai-as-promised'
|
||||||
|
|
||||||
const expect = chai.expect
|
const expect = chai.expect
|
||||||
chai.use(chaiAsPromised)
|
chai.use(chaiAsPromised)
|
||||||
|
|
||||||
describe('cache options', function () {
|
describe('LiquidOptions#cache', function () {
|
||||||
let engine
|
let engine
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
engine = new Liquid({
|
engine = new Liquid({
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user