refactor: moving all ES6 files to src/, working on #83

This commit is contained in:
harttle
2018-08-16 00:22:46 +08:00
parent 9f597843c9
commit 5f634b0b5e
26 changed files with 46 additions and 43 deletions
+138
View File
@@ -0,0 +1,138 @@
'use strict'
const strftime = require('./util/strftime.js')
const _ = require('./util/underscore.js')
const isTruthy = require('./syntax.js').isTruthy
let escapeMap = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&#34;',
"'": '&#39;'
}
let unescapeMap = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&#34;': '"',
'&#39;': "'"
}
let 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),
'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) => {
let amp = Math.pow(10, arg || 0)
return Math.round(v * amp, arg) / amp
},
'rstrip': str => stringify(str).replace(/\s+$/, ''),
'size': v => v.length,
'slice': (v, begin, length) =>
v.substr(begin, length === undefined ? 1 : length),
'sort': (v, arg) => v.sort(arg),
'split': (v, arg) => stringify(v).split(arg),
'strip': (v) => stringify(v).trim(),
'strip_html': v => stringify(v).replace(/<script.*?<\/script>|<!--.*?-->|<style.*?<\/style>|<.*?>/g, ''),
'strip_newlines': v => stringify(v).replace(/\n/g, ''),
'times': (v, arg) => v * arg,
'truncate': (v, l, o) => {
v = stringify(v)
o = (o === undefined) ? '...' : o
l = l || 16
if (v.length <= l) return v
return v.substr(0, l - o.length) + o
},
'truncatewords': (v, l, o) => {
if (o === undefined) o = '...'
let arr = v.split(' ')
let ret = arr.slice(0, l).join(' ')
if (arr.length > l) ret += o
return ret
},
'uniq': function (arr) {
let u = {}
return (arr || []).filter(val => {
if (u.hasOwnProperty(val)) {
return false
}
u[val] = true
return true
})
},
'upcase': str => stringify(str).toUpperCase(),
'url_encode': encodeURIComponent
}
function escape (str) {
return stringify(str).replace(/&|<|>|"|'/g, m => escapeMap[m])
}
function unescape (str) {
return stringify(str).replace(/&(amp|lt|gt|#34|#39);/g, m => unescapeMap[m])
}
function getFixed (v) {
let 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) => {
let f = getMaxFixed(l, r)
return cb(l, r).toFixed(f)
}
}
function registerAll (liquid) {
return _.forOwn(filters, (func, name) => liquid.registerFilter(name, func))
}
function isValidDate (date) {
return date instanceof Date && !isNaN(date.getTime())
}
registerAll.filters = filters
module.exports = registerAll
+189
View File
@@ -0,0 +1,189 @@
const Scope = require('./scope')
const _ = require('./util/underscore.js')
const assert = require('./util/assert.js')
const tokenizer = require('./tokenizer.js')
const statFileAsync = require('./util/fs.js').statFileAsync
const readFileAsync = require('./util/fs.js').readFileAsync
const path = require('path')
const url = require('./util/url.js')
const Render = require('./render.js')
const lexical = require('./lexical.js')
const Tag = require('./tag.js')
const Filter = require('./filter.js')
const Parser = require('./parser')
const Syntax = require('./syntax.js')
const tags = require('./tags')
const filters = require('./filters')
const anySeries = require('./util/promise.js').anySeries
const Errors = require('./util/error.js')
var _engine = {
init: function (tag, filter, options) {
if (options.cache) {
this.cache = {}
}
this.options = options
this.tag = tag
this.filter = filter
this.parser = Parser(tag, filter)
this.renderer = Render()
tags(this)
filters(this)
return this
},
parse: function (html, filepath) {
var tokens = tokenizer.parse(html, filepath, this.options)
return this.parser.parse(tokens)
},
render: function (tpl, ctx, opts) {
opts = _.assign({}, this.options, opts)
var scope = Scope.factory(ctx, opts)
return this.renderer.renderTemplates(tpl, scope)
},
parseAndRender: function (html, ctx, opts) {
return Promise.resolve()
.then(() => this.parse(html))
.then(tpl => this.render(tpl, ctx, opts))
},
renderFile: function (filepath, ctx, opts) {
opts = _.assign({}, opts)
return this.getTemplate(filepath, opts.root)
.then(templates => this.render(templates, ctx, opts))
},
evalValue: function (str, scope) {
var tpl = this.parser.parseValue(str.trim())
return this.renderer.evalValue(tpl, scope)
},
registerFilter: function (name, filter) {
return this.filter.register(name, filter)
},
registerTag: function (name, tag) {
return this.tag.register(name, tag)
},
lookup: function (filepath, root) {
root = this.options.root.concat(root || [])
root = _.uniq(root)
var paths = root.map(root => path.resolve(root, filepath))
return anySeries(paths, path => statFileAsync(path).then(() => path))
.catch((e) => {
e.message = `${e.code}: Failed to lookup ${filepath} in: ${root}`
throw e
})
},
getTemplate: function (filepath, root) {
return typeof XMLHttpRequest === 'undefined'
? this.getTemplateFromFile(filepath, root)
: this.getTemplateFromUrl(filepath, root)
},
getTemplateFromFile: function (filepath, root) {
if (!path.extname(filepath)) {
filepath += this.options.extname
}
return this
.lookup(filepath, root)
.then(filepath => {
if (this.options.cache) {
var tpl = this.cache[filepath]
if (tpl) {
return Promise.resolve(tpl)
}
return readFileAsync(filepath)
.then(str => this.parse(str))
.then(tpl => (this.cache[filepath] = tpl))
} else {
return readFileAsync(filepath).then(str => this.parse(str, filepath))
}
})
},
getTemplateFromUrl: function (filepath, root) {
var fullUrl
if (url.valid(filepath)) {
fullUrl = filepath
} else {
if (!url.extname(filepath)) {
filepath += this.options.extname
}
fullUrl = url.resolve(root || this.options.root, filepath)
}
if (this.options.cache) {
var tpl = this.cache[filepath]
if (tpl) {
return Promise.resolve(tpl)
}
}
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest()
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
var tpl = this.parse(xhr.responseText)
if (this.options.cache) {
this.cache[filepath] = tpl
}
resolve(tpl)
} else {
reject(new Error(xhr.statusText))
}
}
xhr.onerror = () => {
reject(new Error('An error occurred whilst sending the response.'))
}
xhr.open('GET', fullUrl)
xhr.send()
})
},
express: function (opts) {
opts = opts || {}
var self = this
return function (filePath, ctx, callback) {
assert(Array.isArray(this.root) || _.isString(this.root),
'illegal views root, are you using express.js?')
opts.root = this.root
self.renderFile(filePath, ctx, opts)
.then(html => callback(null, html))
.catch(e => callback(e))
}
}
}
function factory (options) {
options = _.assign({
root: ['.'],
cache: false,
extname: '',
dynamicPartials: true,
trim_tag_right: false,
trim_tag_left: false,
trim_value_right: false,
trim_value_left: false,
greedy: true,
strict_filters: false,
strict_variables: false
}, options)
options.root = normalizeStringArray(options.root)
var engine = Object.create(_engine)
engine.init(Tag(), Filter(options), options)
return engine
}
function normalizeStringArray (value) {
if (Array.isArray(value)) return value
if (_.isString(value)) return [value]
return []
}
factory.lexical = lexical
factory.isTruthy = Syntax.isTruthy
factory.isFalsy = Syntax.isFalsy
factory.evalExp = Syntax.evalExp
factory.evalValue = Syntax.evalValue
factory.Types = {
ParseError: Errors.ParseError,
TokenizationEroor: Errors.TokenizationError,
RenderBreakError: Errors.RenderBreakError,
AssertionError: Errors.AssertionError
}
module.exports = factory
+23
View File
@@ -0,0 +1,23 @@
'use strict'
const Liquid = require('..')
const lexical = Liquid.lexical
const re = new RegExp(`(${lexical.identifier.source})\\s*=(.*)`)
const assert = require('../util/assert.js')
const types = require('../scope').types
module.exports = function (liquid) {
liquid.registerTag('assign', {
parse: function (token) {
let match = token.args.match(re)
assert(match, `illegal token ${token.raw}`)
this.key = match[1]
this.value = match[2]
},
render: function (scope) {
let ctx = Object.create(types.AssignScope)
ctx[this.key] = liquid.evalValue(this.value, scope)
scope.push(ctx)
return Promise.resolve('')
}
})
}
+34
View File
@@ -0,0 +1,34 @@
'use strict'
const Liquid = require('..')
const lexical = Liquid.lexical
const re = new RegExp(`(${lexical.identifier.source})`)
const assert = require('../util/assert.js')
const types = require('../scope.js').types
module.exports = function (liquid) {
liquid.registerTag('capture', {
parse: function (tagToken, remainTokens) {
var match = tagToken.args.match(re)
assert(match, `${tagToken.args} not valid identifier`)
this.variable = match[1]
this.templates = []
var stream = liquid.parser.parseStream(remainTokens)
stream.on('tag:endcapture', token => stream.stop())
.on('template', tpl => this.templates.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
return liquid.renderer.renderTemplates(this.templates, scope)
.then((html) => {
let ctx = Object.create(types.CaptureScope)
ctx[this.variable] = html
scope.push(ctx)
})
}
})
}
+41
View File
@@ -0,0 +1,41 @@
const Liquid = require('..')
module.exports = function (liquid) {
liquid.registerTag('case', {
parse: function (tagToken, remainTokens) {
this.cond = tagToken.args
this.cases = []
this.elseTemplates = []
var p = []
var stream = liquid.parser.parseStream(remainTokens)
.on('tag:when', token => {
this.cases.push({
val: token.args,
templates: p = []
})
})
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endcase', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
for (var i = 0; i < this.cases.length; i++) {
var branch = this.cases[i]
var val = Liquid.evalExp(branch.val, scope)
var cond = Liquid.evalExp(this.cond, scope)
if (val === cond) {
return liquid.renderer.renderTemplates(branch.templates, scope)
}
}
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
})
}
+15
View File
@@ -0,0 +1,15 @@
module.exports = function (liquid) {
liquid.registerTag('comment', {
parse: function (tagToken, remainTokens) {
var stream = liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
if (token.name === 'endcomment') stream.stop()
})
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
}
})
}
+43
View File
@@ -0,0 +1,43 @@
const Liquid = require('..')
const lexical = Liquid.lexical
const groupRE = new RegExp(`^(?:(${lexical.value.source})\\s*:\\s*)?(.*)$`)
const candidatesRE = new RegExp(lexical.value.source, 'g')
const assert = require('../util/assert.js')
module.exports = function (liquid) {
liquid.registerTag('cycle', {
parse: function (tagToken, remainTokens) {
var match = groupRE.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.group = match[1] || ''
var candidates = match[2]
this.candidates = []
while ((match = candidatesRE.exec(candidates))) {
this.candidates.push(match[0])
}
assert(this.candidates.length, `empty candidates: ${tagToken.raw}`)
},
render: function (scope, hash) {
var group = Liquid.evalValue(this.group, scope)
var fingerprint = `cycle:${group}:` + this.candidates.join(',')
var groups = scope.opts.groups = scope.opts.groups || {}
var idx = groups[fingerprint]
if (idx === undefined) {
idx = groups[fingerprint] = 0
}
var candidate = this.candidates[idx]
idx = (idx + 1) % this.candidates.length
groups[fingerprint] = idx
return Promise.resolve(Liquid.evalValue(candidate, scope))
}
})
}
+32
View File
@@ -0,0 +1,32 @@
'use strict'
const Liquid = require('..')
const lexical = Liquid.lexical
const assert = require('../util/assert.js')
const types = require('../scope').types
module.exports = function (liquid) {
liquid.registerTag('decrement', {
parse: function (token) {
var match = token.args.match(lexical.identifier)
assert(match, `illegal identifier ${token.args}`)
this.variable = match[0]
},
render: function (scope, hash) {
let context = scope.findContextFor(
this.variable,
ctx => {
return Object.getPrototypeOf(ctx) !== types.CaptureScope &&
Object.getPrototypeOf(ctx) !== types.AssignScope
}
)
if (!context) {
context = Object.create(types.DecrementScope)
scope.unshift(context)
}
if (typeof context[this.variable] !== 'number') {
context[this.variable] = 0
}
return --context[this.variable]
}
})
}
+96
View File
@@ -0,0 +1,96 @@
const Liquid = require('..')
const lexical = Liquid.lexical
const mapSeries = require('../util/promise.js').mapSeries
const _ = require('../util/underscore.js')
const RenderBreakError = Liquid.Types.RenderBreakError
const assert = require('../util/assert.js')
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
`(${lexical.value.source})` +
`(?:\\s+${lexical.hash.source})*` +
`(?:\\s+(reversed))?` +
`(?:\\s+${lexical.hash.source})*$`)
module.exports = function (liquid) {
liquid.registerTag('for', {
parse: function (tagToken, remainTokens) {
var match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1]
this.collection = match[2]
this.reversed = !!match[3]
this.templates = []
this.elseTemplates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates))
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endfor', () => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
var collection = Liquid.evalExp(this.collection, scope)
if (!Array.isArray(collection)) {
if (_.isString(collection) && collection.length > 0) {
collection = [collection]
} else if (_.isObject(collection)) {
collection = Object.keys(collection).map((key) => [key, collection[key]])
}
}
if (!Array.isArray(collection) || !collection.length) {
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
var offset = hash.offset || 0
var limit = (hash.limit === undefined) ? collection.length : hash.limit
collection = collection.slice(offset, offset + limit)
if (this.reversed) collection.reverse()
var contexts = collection.map((item, i) => {
var ctx = {}
ctx[this.variable] = item
ctx.forloop = {
first: i === 0,
index: i + 1,
index0: i,
last: i === collection.length - 1,
length: collection.length,
rindex: collection.length - i,
rindex0: collection.length - i - 1
}
return ctx
})
var html = ''
return mapSeries(contexts, (context) => {
return Promise.resolve()
.then(() => scope.push(context))
.then(() => liquid.renderer.renderTemplates(this.templates, scope))
.then(partial => (html += partial))
.catch(e => {
if (e instanceof RenderBreakError) {
html += e.resolvedHTML
if (e.message === 'continue') return
}
throw e
})
.then(() => scope.pop(context))
}).catch((e) => {
if (e instanceof RenderBreakError && e.message === 'break') {
return
}
throw e
}).then(() => html)
}
})
}
+43
View File
@@ -0,0 +1,43 @@
const Liquid = require('..')
module.exports = function (liquid) {
liquid.registerTag('if', {
parse: function (tagToken, remainTokens) {
this.branches = []
this.elseTemplates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
.on('start', () => this.branches.push({
cond: tagToken.args,
templates: (p = [])
}))
.on('tag:elsif', token => {
this.branches.push({
cond: token.args,
templates: p = []
})
})
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endif', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
for (var i = 0; i < this.branches.length; i++) {
var branch = this.branches[i]
var cond = Liquid.evalExp(branch.cond, scope)
if (Liquid.isTruthy(cond)) {
return liquid.renderer.renderTemplates(branch.templates, scope)
}
}
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
})
}
+64
View File
@@ -0,0 +1,64 @@
'use strict'
const Liquid = require('..')
const lexical = Liquid.lexical
const withRE = new RegExp(`with\\s+(${lexical.value.source})`)
const staticFileRE = /[^\s,]+/
const assert = require('../util/assert.js')
module.exports = function (liquid) {
liquid.registerTag('include', {
parse: function (token) {
let match = staticFileRE.exec(token.args)
if (match) {
this.staticValue = match[0]
}
match = lexical.value.exec(token.args)
if (match) {
this.value = match[0]
}
match = withRE.exec(token.args)
if (match) {
this.with = match[1]
}
},
render: function (scope, hash) {
let pFilepath
if (scope.opts.dynamicPartials) {
if (lexical.quotedLine.exec(this.value)) {
let template = this.value.slice(1, -1)
pFilepath = liquid.parseAndRender(template, scope.getAll(), scope.opts)
} else {
pFilepath = Promise.resolve(Liquid.evalValue(this.value, scope))
}
} else {
pFilepath = Promise.resolve(this.staticValue)
}
let originBlocks = scope.opts.blocks
let originBlockMode = scope.opts.blockMode
return pFilepath
.then(filepath => {
assert(filepath, `cannot include with empty filename`)
scope.opts.blocks = {}
scope.opts.blockMode = 'output'
if (this.with) {
hash[filepath] = Liquid.evalValue(this.with, scope)
}
return liquid.getTemplate(filepath, scope.opts.root)
})
.then(templates => {
scope.push(hash)
return liquid.renderer.renderTemplates(templates, scope)
})
.then((html) => {
scope.pop(hash)
scope.opts.blocks = originBlocks
scope.opts.blockMode = originBlockMode
return html
})
}
})
}
+34
View File
@@ -0,0 +1,34 @@
'use strict'
const Liquid = require('..')
const assert = require('../util/assert.js')
const lexical = Liquid.lexical
const types = require('../scope').types
module.exports = function (liquid) {
liquid.registerTag('increment', {
parse: function (token) {
let match = token.args.match(lexical.identifier)
assert(match, `illegal identifier ${token.args}`)
this.variable = match[0]
},
render: function (scope, hash) {
let context = scope.findContextFor(
this.variable,
ctx => {
return Object.getPrototypeOf(ctx) !== types.CaptureScope &&
Object.getPrototypeOf(ctx) !== types.AssignScope
}
)
if (!context) {
context = Object.create(types.IncrementScope)
scope.unshift(context)
}
if (typeof context[this.variable] !== 'number') {
context[this.variable] = 0
}
let val = context[this.variable]
context[this.variable]++
return val
}
})
}
+16
View File
@@ -0,0 +1,16 @@
module.exports = function (engine) {
require('./assign.js')(engine)
require('./capture.js')(engine)
require('./case.js')(engine)
require('./comment.js')(engine)
require('./cycle.js')(engine)
require('./decrement.js')(engine)
require('./for.js')(engine)
require('./if.js')(engine)
require('./include.js')(engine)
require('./increment.js')(engine)
require('./layout.js')(engine)
require('./raw.js')(engine)
require('./tablerow.js')(engine)
require('./unless.js')(engine)
}
+82
View File
@@ -0,0 +1,82 @@
const Liquid = require('..')
const lexical = Liquid.lexical
const assert = require('../util/assert.js')
const staticFileRE = /\S+/
/*
* blockMode:
* * "store": store rendered html into blocks
* * "output": output rendered html
*/
module.exports = function (liquid) {
liquid.registerTag('layout', {
parse: function (token, remainTokens) {
var match = staticFileRE.exec(token.args)
if (match) {
this.staticLayout = match[0]
}
match = lexical.value.exec(token.args)
if (match) {
this.layout = match[0]
}
this.tpls = liquid.parser.parse(remainTokens)
},
render: function (scope, hash) {
var layout = scope.opts.dynamicPartials ? Liquid.evalValue(this.layout, scope) : this.staticLayout
assert(layout, `cannot apply layout with empty filename`)
// render the remaining tokens immediately
scope.opts.blockMode = 'store'
return liquid.renderer.renderTemplates(this.tpls, scope)
.then(html => {
if (scope.opts.blocks[''] === undefined) {
scope.opts.blocks[''] = html
}
return liquid.getTemplate(layout, scope.opts.root)
})
.then(templates => {
scope.push(hash)
scope.opts.blockMode = 'output'
return liquid.renderer.renderTemplates(templates, scope)
})
.then(partial => {
scope.pop(hash)
return partial
})
}
})
liquid.registerTag('block', {
parse: function (token, remainTokens) {
var match = /\w+/.exec(token.args)
this.block = match ? match[0] : ''
this.tpls = []
var stream = liquid.parser.parseStream(remainTokens)
.on('tag:endblock', () => stream.stop())
.on('template', tpl => this.tpls.push(tpl))
.on('end', () => {
throw new Error(`tag ${token.raw} not closed`)
})
stream.start()
},
render: function (scope) {
return Promise.resolve(scope.opts.blocks[this.block])
.then(html => html === undefined
// render default block
? liquid.renderer.renderTemplates(this.tpls, scope)
// use child-defined block
: html)
.then(html => {
if (scope.opts.blockMode === 'store') {
scope.opts.blocks[this.block] = html
return ''
}
return html
})
}
})
}
+21
View File
@@ -0,0 +1,21 @@
module.exports = function (liquid) {
liquid.registerTag('raw', {
parse: function (tagToken, remainTokens) {
this.tokens = []
var stream = liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
if (token.name === 'endraw') stream.stop()
else this.tokens.push(token)
})
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
return this.tokens.map(token => token.raw).join('')
}
})
}
+82
View File
@@ -0,0 +1,82 @@
const Liquid = require('..')
const mapSeries = require('../util/promise.js').mapSeries
const lexical = Liquid.lexical
const assert = require('../util/assert.js')
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
`(${lexical.value.source})` +
`(?:\\s+${lexical.hash.source})*$`)
module.exports = function (liquid) {
liquid.registerTag('tablerow', {
parse: function (tagToken, remainTokens) {
var match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1]
this.collection = match[2]
this.templates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates))
.on('tag:endtablerow', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
var collection = Liquid.evalExp(this.collection, scope) || []
var html = ''
var offset = hash.offset || 0
var limit = (hash.limit === undefined) ? collection.length : hash.limit
var cols = hash.cols
var row
var col
// build array of arguments to pass to sequential promises...
collection = collection.slice(offset, offset + limit)
if (!cols) cols = collection.length
var contexts = collection.map((item, i) => {
var ctx = {}
ctx[this.variable] = item
return ctx
})
return mapSeries(contexts,
(context, idx) => {
row = Math.floor(idx / cols) + 1
col = (idx % cols) + 1
if (col === 1) {
if (row !== 1) {
html += '</tr>'
}
html += `<tr class="row${row}">`
}
html += `<td class="col${col}">`
scope.push(context)
return liquid.renderer
.renderTemplates(this.templates, scope)
.then((partial) => {
scope.pop(context)
html += partial
html += '</td>'
return html
})
})
.then(() => {
if (row > 0) {
html += '</tr>'
}
return html
})
}
})
}
+31
View File
@@ -0,0 +1,31 @@
const Liquid = require('..')
module.exports = function (liquid) {
liquid.registerTag('unless', {
parse: function (tagToken, remainTokens) {
this.templates = []
this.elseTemplates = []
var p
var stream = liquid.parser.parseStream(remainTokens)
.on('start', x => {
p = this.templates
this.cond = tagToken.args
})
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endunless', token => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
var cond = Liquid.evalExp(this.cond, scope)
return Liquid.isFalsy(cond)
? liquid.renderer.renderTemplates(this.templates, scope)
: liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
})
}