mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-15 04:10:40 -07:00
feat: renderSync, parseAndRenderSync and renderFileSync, see #48
This commit is contained in:
@@ -12,6 +12,8 @@ export default {
|
||||
this.value = match[2]
|
||||
},
|
||||
render: async function (ctx: Context) {
|
||||
ctx.front()[this.key] = await this.liquid.evalValue(this.value, ctx)
|
||||
ctx.front()[this.key] = ctx.sync
|
||||
? this.liquid.evalValueSync(this.value, ctx)
|
||||
: await this.liquid.evalValue(this.value, ctx)
|
||||
}
|
||||
} as ITagImplOptions
|
||||
|
||||
@@ -17,9 +17,13 @@ export default {
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
const blocks = ctx.getRegister('blocks')
|
||||
const childDefined = blocks[this.block]
|
||||
const r = this.liquid.renderer
|
||||
const html = childDefined !== undefined
|
||||
? childDefined
|
||||
: await this.liquid.renderer.renderTemplates(this.tpls, ctx)
|
||||
: (ctx.sync
|
||||
? r.renderTemplatesSync(this.tpls, ctx)
|
||||
: await r.renderTemplates(this.tpls, ctx)
|
||||
)
|
||||
|
||||
if (ctx.getRegister('blockMode', BlockMode.OUTPUT) === BlockMode.STORE) {
|
||||
blocks[this.block] = html
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { RenderBreakError } from '../../util/error'
|
||||
import { Emitter, Context, Hash } from '../../types'
|
||||
|
||||
export default {
|
||||
render: async function () {
|
||||
throw new RenderBreakError('break')
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
emitter.break = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,10 @@ export default {
|
||||
stream.start()
|
||||
},
|
||||
render: async function (ctx: Context) {
|
||||
const html = await this.liquid.renderer.renderTemplates(this.templates, ctx)
|
||||
const r = this.liquid.renderer
|
||||
const html = ctx.sync
|
||||
? r.renderTemplatesSync(this.templates, ctx)
|
||||
: await r.renderTemplates(this.templates, ctx)
|
||||
ctx.front()[this.variable] = html
|
||||
}
|
||||
} as ITagImplOptions
|
||||
|
||||
@@ -25,15 +25,30 @@ export default {
|
||||
},
|
||||
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
const r = this.liquid.renderer
|
||||
for (let i = 0; i < this.cases.length; i++) {
|
||||
const branch = this.cases[i]
|
||||
const val = new Expression(branch.val).value(ctx)
|
||||
const cond = new Expression(this.cond).value(ctx)
|
||||
const val = await new Expression(branch.val).value(ctx)
|
||||
const cond = await new Expression(this.cond).value(ctx)
|
||||
if (val === cond) {
|
||||
this.liquid.renderer.renderTemplates(branch.templates, ctx, emitter)
|
||||
await r.renderTemplates(branch.templates, ctx, emitter)
|
||||
return
|
||||
}
|
||||
}
|
||||
this.liquid.renderer.renderTemplates(this.elseTemplates, ctx, emitter)
|
||||
await r.renderTemplates(this.elseTemplates, ctx, emitter)
|
||||
},
|
||||
|
||||
renderSync: function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
const r = this.liquid.renderer
|
||||
for (let i = 0; i < this.cases.length; i++) {
|
||||
const branch = this.cases[i]
|
||||
const val = new Expression(branch.val).valueSync(ctx)
|
||||
const cond = new Expression(this.cond).valueSync(ctx)
|
||||
if (val === cond) {
|
||||
r.renderTemplatesSync(branch.templates, ctx, emitter)
|
||||
return
|
||||
}
|
||||
}
|
||||
r.renderTemplatesSync(this.elseTemplates, ctx, emitter)
|
||||
}
|
||||
} as ITagImplOptions
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { RenderBreakError } from '../../util/error'
|
||||
import { Emitter, Context, Hash } from '../../types'
|
||||
|
||||
export default {
|
||||
render: async function () {
|
||||
throw new RenderBreakError('continue')
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
emitter.continue = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,9 @@ export default {
|
||||
},
|
||||
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
const group = this.group.value(ctx)
|
||||
const group = ctx.sync
|
||||
? this.group.valueSync(ctx)
|
||||
: await this.group.value(ctx)
|
||||
const fingerprint = `cycle:${group}:` + this.candidates.join(',')
|
||||
const groups = ctx.getRegister('cycle')
|
||||
let idx = groups[fingerprint]
|
||||
@@ -34,6 +36,9 @@ export default {
|
||||
const candidate = this.candidates[idx]
|
||||
idx = (idx + 1) % this.candidates.length
|
||||
groups[fingerprint] = idx
|
||||
emitter.write(new Expression(candidate).value(ctx))
|
||||
const html = ctx.sync
|
||||
? new Expression(candidate).valueSync(ctx)
|
||||
: await new Expression(candidate).value(ctx)
|
||||
emitter.write(html)
|
||||
}
|
||||
} as ITagImplOptions
|
||||
|
||||
+18
-11
@@ -37,7 +37,10 @@ export default {
|
||||
stream.start()
|
||||
},
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
let collection = new Expression(this.collection).value(ctx)
|
||||
const r = this.liquid.renderer
|
||||
let collection = ctx.sync
|
||||
? new Expression(this.collection).valueSync(ctx)
|
||||
: await new Expression(this.collection).value(ctx)
|
||||
|
||||
if (!isArray(collection)) {
|
||||
if (isString(collection) && collection.length > 0) {
|
||||
@@ -47,7 +50,9 @@ export default {
|
||||
}
|
||||
}
|
||||
if (!isArray(collection) || !collection.length) {
|
||||
this.liquid.renderer.renderTemplates(this.elseTemplates, ctx, emitter)
|
||||
ctx.sync
|
||||
? r.renderTemplatesSync(this.elseTemplates, ctx, emitter)
|
||||
: await r.renderTemplates(this.elseTemplates, ctx, emitter)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -57,17 +62,19 @@ export default {
|
||||
collection = collection.slice(offset, offset + limit)
|
||||
if (this.reversed) collection.reverse()
|
||||
|
||||
const context = { forloop: new ForloopDrop(collection.length) }
|
||||
ctx.push(context)
|
||||
const scope = { forloop: new ForloopDrop(collection.length) }
|
||||
ctx.push(scope)
|
||||
for (const item of collection) {
|
||||
context[this.variable] = item
|
||||
try {
|
||||
await this.liquid.renderer.renderTemplates(this.templates, ctx, emitter)
|
||||
} catch (e) {
|
||||
if (e.name !== 'RenderBreakError') throw e
|
||||
if (e.message === 'break') break
|
||||
scope[this.variable] = item
|
||||
ctx.sync
|
||||
? r.renderTemplatesSync(this.templates, ctx, emitter)
|
||||
: await r.renderTemplates(this.templates, ctx, emitter)
|
||||
if (emitter.break) {
|
||||
emitter.break = false
|
||||
break
|
||||
}
|
||||
context.forloop.next()
|
||||
emitter.continue = false
|
||||
scope.forloop.next()
|
||||
}
|
||||
ctx.pop()
|
||||
}
|
||||
|
||||
+18
-3
@@ -28,13 +28,28 @@ export default {
|
||||
},
|
||||
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
const r = this.liquid.renderer
|
||||
|
||||
for (const branch of this.branches) {
|
||||
const cond = new Expression(branch.cond).value(ctx)
|
||||
const cond = await new Expression(branch.cond).value(ctx)
|
||||
if (isTruthy(cond)) {
|
||||
await this.liquid.renderer.renderTemplates(branch.templates, ctx, emitter)
|
||||
await r.renderTemplates(branch.templates, ctx, emitter)
|
||||
return
|
||||
}
|
||||
}
|
||||
await this.liquid.renderer.renderTemplates(this.elseTemplates, ctx, emitter)
|
||||
await r.renderTemplates(this.elseTemplates, ctx, emitter)
|
||||
},
|
||||
|
||||
renderSync: function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
const r = this.liquid.renderer
|
||||
|
||||
for (const branch of this.branches) {
|
||||
const cond = new Expression(branch.cond).valueSync(ctx)
|
||||
if (isTruthy(cond)) {
|
||||
r.renderTemplatesSync(branch.templates, ctx, emitter)
|
||||
return
|
||||
}
|
||||
}
|
||||
r.renderTemplatesSync(this.elseTemplates, ctx, emitter)
|
||||
}
|
||||
} as ITagImplOptions
|
||||
|
||||
@@ -17,14 +17,14 @@ export default {
|
||||
match = withRE.exec(token.args)
|
||||
if (match) this.with = match[1]
|
||||
},
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
renderSync: function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
let filepath
|
||||
if (ctx.opts.dynamicPartials) {
|
||||
if (quotedLine.exec(this.value)) {
|
||||
const template = this.value.slice(1, -1)
|
||||
filepath = await this.liquid.parseAndRender(template, ctx.getAll(), ctx.opts)
|
||||
filepath = this.liquid.parseAndRenderSync(template, ctx.getAll(), ctx.opts)
|
||||
} else {
|
||||
filepath = new Expression(this.value).value(ctx)
|
||||
filepath = new Expression(this.value).valueSync(ctx)
|
||||
}
|
||||
} else {
|
||||
filepath = this.staticValue
|
||||
@@ -37,7 +37,37 @@ export default {
|
||||
ctx.setRegister('blocks', {})
|
||||
ctx.setRegister('blockMode', BlockMode.OUTPUT)
|
||||
if (this.with) {
|
||||
hash[filepath] = new Expression(this.with).evaluate(ctx)
|
||||
hash[filepath] = new Expression(this.with).evaluateSync(ctx)
|
||||
}
|
||||
const templates = this.liquid.getTemplateSync(filepath, ctx.opts)
|
||||
ctx.push(hash)
|
||||
this.liquid.renderer.renderTemplatesSync(templates, ctx, emitter)
|
||||
ctx.pop()
|
||||
ctx.setRegister('blocks', originBlocks)
|
||||
ctx.setRegister('blockMode', originBlockMode)
|
||||
},
|
||||
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
let filepath
|
||||
if (ctx.opts.dynamicPartials) {
|
||||
if (quotedLine.exec(this.value)) {
|
||||
const template = this.value.slice(1, -1)
|
||||
filepath = await this.liquid.parseAndRender(template, ctx.getAll(), ctx.opts)
|
||||
} else {
|
||||
filepath = await new Expression(this.value).value(ctx)
|
||||
}
|
||||
} else {
|
||||
filepath = this.staticValue
|
||||
}
|
||||
assert(filepath, `cannot include with empty filename`)
|
||||
|
||||
const originBlocks = ctx.getRegister('blocks')
|
||||
const originBlockMode = ctx.getRegister('blockMode')
|
||||
|
||||
ctx.setRegister('blocks', {})
|
||||
ctx.setRegister('blockMode', BlockMode.OUTPUT)
|
||||
if (this.with) {
|
||||
hash[filepath] = await new Expression(this.with).evaluate(ctx)
|
||||
}
|
||||
const templates = await this.liquid.getTemplate(filepath, ctx.opts)
|
||||
ctx.push(hash)
|
||||
|
||||
@@ -21,21 +21,31 @@ export default {
|
||||
},
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
const layout = ctx.opts.dynamicPartials
|
||||
? await (new Expression(this.layout).value(ctx))
|
||||
? (ctx.sync
|
||||
? new Expression(this.layout).valueSync(ctx)
|
||||
: await new Expression(this.layout).value(ctx)
|
||||
)
|
||||
: this.staticLayout
|
||||
assert(layout, `cannot apply layout with empty filename`)
|
||||
|
||||
// render the remaining tokens immediately
|
||||
ctx.setRegister('blockMode', BlockMode.STORE)
|
||||
const blocks = ctx.getRegister('blocks')
|
||||
const html = await this.liquid.renderer.renderTemplates(this.tpls, ctx)
|
||||
const r = this.liquid.renderer
|
||||
const html = ctx.sync
|
||||
? r.renderTemplatesSync(this.tpls, ctx)
|
||||
: await r.renderTemplates(this.tpls, ctx)
|
||||
if (blocks[''] === undefined) {
|
||||
blocks[''] = html
|
||||
}
|
||||
const templates = await this.liquid.getTemplate(layout, ctx.opts)
|
||||
const templates = ctx.sync
|
||||
? this.liquid.getTemplateSync(layout, ctx.opts)
|
||||
: await this.liquid.getTemplate(layout, ctx.opts)
|
||||
ctx.push(hash)
|
||||
ctx.setRegister('blockMode', BlockMode.OUTPUT)
|
||||
const partial = await this.liquid.renderer.renderTemplates(templates, ctx)
|
||||
const partial = ctx.sync
|
||||
? r.renderTemplatesSync(templates, ctx)
|
||||
: await r.renderTemplates(templates, ctx)
|
||||
ctx.pop()
|
||||
emitter.write(partial)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ export default {
|
||||
})
|
||||
stream.start()
|
||||
},
|
||||
render: function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
emitter.write(this.tokens.map((token: Token) => token.raw).join(''))
|
||||
render: function (ctx: Context) {
|
||||
return this.tokens.map((token: Token) => token.raw).join('')
|
||||
}
|
||||
} as ITagImplOptions
|
||||
|
||||
@@ -29,13 +29,16 @@ export default {
|
||||
},
|
||||
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
let collection = new Expression(this.collection).value(ctx) || []
|
||||
let collection = ctx.sync
|
||||
? new Expression(this.collection).valueSync(ctx) || []
|
||||
: await new Expression(this.collection).value(ctx) || []
|
||||
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 r = this.liquid.renderer
|
||||
const tablerowloop = new TablerowloopDrop(collection.length, cols)
|
||||
const scope = { tablerowloop }
|
||||
ctx.push(scope)
|
||||
@@ -47,7 +50,9 @@ export default {
|
||||
emitter.write(`<tr class="row${tablerowloop.row()}">`)
|
||||
}
|
||||
emitter.write(`<td class="col${tablerowloop.col()}">`)
|
||||
await this.liquid.renderer.renderTemplates(this.templates, ctx, emitter)
|
||||
ctx.sync
|
||||
? r.renderTemplatesSync(this.templates, ctx, emitter)
|
||||
: await r.renderTemplates(this.templates, ctx, emitter)
|
||||
emitter.write('</td>')
|
||||
}
|
||||
if (collection.length) emitter.write('</tr>')
|
||||
|
||||
@@ -20,10 +20,19 @@ export default {
|
||||
stream.start()
|
||||
},
|
||||
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
const cond = new Expression(this.cond).value(ctx)
|
||||
renderSync: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
const r = this.liquid.renderer
|
||||
const cond = new Expression(this.cond).valueSync(ctx)
|
||||
isFalsy(cond)
|
||||
? await this.liquid.renderer.renderTemplates(this.templates, ctx, emitter)
|
||||
: await this.liquid.renderer.renderTemplates(this.elseTemplates, ctx, emitter)
|
||||
? r.renderTemplatesSync(this.templates, ctx, emitter)
|
||||
: r.renderTemplatesSync(this.elseTemplates, ctx, emitter)
|
||||
},
|
||||
|
||||
render: async function (ctx: Context, hash: Hash, emitter: Emitter) {
|
||||
const r = this.liquid.renderer
|
||||
const cond = await new Expression(this.cond).value(ctx)
|
||||
await isFalsy(cond)
|
||||
? r.renderTemplates(this.templates, ctx, emitter)
|
||||
: r.renderTemplates(this.elseTemplates, ctx, emitter)
|
||||
}
|
||||
} as ITagImplOptions
|
||||
|
||||
@@ -9,8 +9,10 @@ export class Context {
|
||||
private scopes: Scope[] = [{}]
|
||||
private registers = {}
|
||||
public environments: Scope
|
||||
public sync: boolean
|
||||
public opts: NormalizedFullOptions
|
||||
public constructor (ctx: object = {}, opts?: NormalizedFullOptions) {
|
||||
public constructor (ctx: object = {}, opts?: NormalizedFullOptions, sync: boolean = false) {
|
||||
this.sync = sync
|
||||
this.opts = applyDefault(opts)
|
||||
this.environments = ctx
|
||||
}
|
||||
|
||||
+15
-1
@@ -44,8 +44,22 @@ async function readFile (url: string): Promise<string> {
|
||||
})
|
||||
}
|
||||
|
||||
function readFileSync (url: string): string {
|
||||
const xhr = new XMLHttpRequest()
|
||||
xhr.open('GET', url, false)
|
||||
xhr.send()
|
||||
if (xhr.status < 200 || xhr.status >= 300) {
|
||||
throw new Error(xhr.statusText)
|
||||
}
|
||||
return xhr.responseText as string
|
||||
}
|
||||
|
||||
async function exists () {
|
||||
return true
|
||||
}
|
||||
|
||||
export default { readFile, resolve, exists } as IFS
|
||||
function existsSync () {
|
||||
return true
|
||||
}
|
||||
|
||||
export default { readFile, resolve, exists, existsSync, readFileSync } as IFS
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
export default interface IFS {
|
||||
exists: (filepath: string) => Promise<boolean>;
|
||||
readFile: (filepath: string) => Promise<string>;
|
||||
existsSync: (filepath: string) => boolean;
|
||||
readFileSync: (filepath: string) => string;
|
||||
resolve: (root: string, file: string, ext: string) => string;
|
||||
}
|
||||
|
||||
+12
-1
@@ -1,6 +1,6 @@
|
||||
import * as _ from '../util/underscore'
|
||||
import { resolve, extname } from 'path'
|
||||
import { stat, readFile } from 'fs'
|
||||
import { stat, statSync, readFile, readFileSync } from 'fs'
|
||||
import IFS from './ifs'
|
||||
|
||||
const statAsync = _.promisify(stat)
|
||||
@@ -13,6 +13,17 @@ const fs: IFS = {
|
||||
readFile: filepath => {
|
||||
return readFileAsync(filepath, 'utf8')
|
||||
},
|
||||
existsSync: (filepath: string) => {
|
||||
try {
|
||||
statSync(filepath)
|
||||
return true
|
||||
} catch (err) {
|
||||
return false
|
||||
}
|
||||
},
|
||||
readFileSync: filepath => {
|
||||
return readFileSync(filepath, 'utf8')
|
||||
},
|
||||
resolve: (root: string, file: string, ext: string) => {
|
||||
if (!extname(file)) file += ext
|
||||
return resolve(root, file)
|
||||
|
||||
@@ -88,7 +88,7 @@ export function applyDefault (options?: NormalizedOptions): NormalizedFullOption
|
||||
return { ...defaultOptions, ...options }
|
||||
}
|
||||
|
||||
function normalizeStringArray (value: any): string[] {
|
||||
export function normalizeStringArray (value: any): string[] {
|
||||
if (_.isArray(value)) return value as string[]
|
||||
if (_.isString(value)) return [value as string]
|
||||
return []
|
||||
|
||||
+80
-27
@@ -11,9 +11,12 @@ import { ITagImplOptions } from './template/tag/itag-impl-options'
|
||||
import { Value } from './template/value'
|
||||
import builtinTags from './builtin/tags'
|
||||
import builtinFilters from './builtin/filters'
|
||||
import { LiquidOptions, NormalizedFullOptions, applyDefault, normalize } from './liquid-options'
|
||||
import { LiquidOptions, normalizeStringArray, NormalizedFullOptions, applyDefault, normalize } from './liquid-options'
|
||||
import { FilterImplOptions } from './template/filter/filter-impl-options'
|
||||
import IFS from './fs/ifs'
|
||||
|
||||
type GetTemplateResult = ITemplate[] | undefined
|
||||
|
||||
export * from './types'
|
||||
|
||||
export class Liquid {
|
||||
@@ -34,47 +37,72 @@ export class Liquid {
|
||||
_.forOwn(builtinTags, (conf, name) => this.registerTag(name, conf))
|
||||
_.forOwn(builtinFilters, (handler, name) => this.registerFilter(name, handler))
|
||||
}
|
||||
public parse (html: string, filepath?: string) {
|
||||
public parse (html: string, filepath?: string): ITemplate[] {
|
||||
const tokens = this.tokenizer.tokenize(html, filepath)
|
||||
return this.parser.parse(tokens)
|
||||
}
|
||||
public render (tpl: ITemplate[], scope?: object, opts?: LiquidOptions) {
|
||||
public render (tpl: ITemplate[], scope?: object, opts?: LiquidOptions): Promise<string> {
|
||||
const options = { ...this.options, ...normalize(opts) }
|
||||
const ctx = new Context(scope, options)
|
||||
return this.renderer.renderTemplates(tpl, ctx)
|
||||
}
|
||||
public async parseAndRender (html: string, ctx?: object, opts?: LiquidOptions) {
|
||||
const tpl = await this.parse(html)
|
||||
return this.render(tpl, ctx, opts)
|
||||
public renderSync (tpl: ITemplate[], scope?: object, opts?: LiquidOptions): string {
|
||||
const options = { ...this.options, ...normalize(opts) }
|
||||
const ctx = new Context(scope, options, true)
|
||||
return this.renderer.renderTemplatesSync(tpl, ctx)
|
||||
}
|
||||
public async getTemplate (file: string, opts?: LiquidOptions) {
|
||||
const options = normalize(opts)
|
||||
const roots = options.root ? [...options.root, ...this.options.root] : this.options.root
|
||||
const paths = roots.map(root => this.fs.resolve(root, file, this.options.extname))
|
||||
public async parseAndRender (html: string, scope?: object, opts?: LiquidOptions): Promise<string> {
|
||||
const tpl = this.parse(html)
|
||||
return this.render(tpl, scope, opts)
|
||||
}
|
||||
public parseAndRenderSync (html: string, scope?: object, opts?: LiquidOptions): string {
|
||||
const tpl = this.parse(html)
|
||||
return this.renderSync(tpl, scope, opts)
|
||||
}
|
||||
public getTemplateSync (file: string, opts?: LiquidOptions): ITemplate[] {
|
||||
const options = { ...this.options, ...normalize(opts) }
|
||||
const paths = options.root.map(root => this.fs.resolve(root, file, options.extname))
|
||||
|
||||
for (const filepath of paths) {
|
||||
if (this.options.cache && this.cache[filepath]) return this.cache[filepath]
|
||||
|
||||
if (!(await this.fs.exists(filepath))) continue
|
||||
|
||||
const value = this.parse(await this.fs.readFile(filepath), filepath)
|
||||
if (this.options.cache) this.cache[filepath] = value
|
||||
return value
|
||||
const tpl = this.respectCache(filepath, () => {
|
||||
if (!(this.fs.existsSync(filepath))) return
|
||||
return this.parse(this.fs.readFileSync(filepath), filepath)
|
||||
})
|
||||
if (tpl) return tpl
|
||||
}
|
||||
|
||||
const err = new Error('ENOENT') as any
|
||||
err.message = `ENOENT: Failed to lookup "${file}" in "${roots}"`
|
||||
err.code = 'ENOENT'
|
||||
throw err
|
||||
throw this.lookupError(file, options.root)
|
||||
}
|
||||
public async getTemplate (file: string, opts?: LiquidOptions): Promise<ITemplate[]> {
|
||||
const options = { ...this.options, ...normalize(opts) }
|
||||
const paths = options.root.map(root => this.fs.resolve(root, file, options.extname))
|
||||
|
||||
for (const filepath of paths) {
|
||||
const tpl = await this.respectCache(filepath, async () => {
|
||||
if (!(await this.fs.exists(filepath))) return
|
||||
return this.parse(await this.fs.readFile(filepath), filepath)
|
||||
})
|
||||
if (tpl !== undefined) return tpl
|
||||
}
|
||||
throw this.lookupError(file, options.root)
|
||||
}
|
||||
public async renderFile (file: string, ctx?: object, opts?: LiquidOptions) {
|
||||
const options = normalize(opts)
|
||||
const templates = await this.getTemplate(file, options)
|
||||
const templates = await this.getTemplate(file, opts)
|
||||
return this.render(templates, ctx, opts)
|
||||
}
|
||||
public evalValue (str: string, ctx: Context) {
|
||||
public renderFileSync (file: string, ctx?: object, opts?: LiquidOptions) {
|
||||
const options = normalize(opts)
|
||||
const templates = this.getTemplateSync(file, options)
|
||||
return this.renderSync(templates, ctx, opts)
|
||||
}
|
||||
public async evalValue (str: string, ctx: Context): Promise<any> {
|
||||
return new Value(str, this.options.strictFilters).value(ctx)
|
||||
}
|
||||
|
||||
public evalValueSync (str: string, ctx: Context): any {
|
||||
return new Value(str, this.options.strictFilters).valueSync(ctx)
|
||||
}
|
||||
|
||||
public registerFilter (name: string, filter: FilterImplOptions) {
|
||||
return Filter.register(name, filter)
|
||||
}
|
||||
@@ -85,10 +113,35 @@ export class Liquid {
|
||||
return plugin.call(this, Liquid)
|
||||
}
|
||||
public express () {
|
||||
const self = this
|
||||
const self = this // eslint-disable-line
|
||||
return function (this: any, filePath: string, ctx: object, cb: (err: Error | null, html?: string) => void) {
|
||||
const opts = { root: this.root }
|
||||
const opts = { root: [...normalizeStringArray(this.root), ...self.options.root] }
|
||||
self.renderFile(filePath, ctx, opts).then(html => cb(null, html), cb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private lookupError (file: string, roots: string[]) {
|
||||
const err = new Error('ENOENT') as any
|
||||
err.message = `ENOENT: Failed to lookup "${file}" in "${roots}"`
|
||||
err.code = 'ENOENT'
|
||||
return err
|
||||
}
|
||||
|
||||
private setCache<T extends GetTemplateResult> (filepath: string, tpl: T): T {
|
||||
if (tpl === undefined) return tpl
|
||||
this.cache[filepath] = tpl
|
||||
return tpl
|
||||
}
|
||||
|
||||
private respectCache (filepath: string, resolver: () => GetTemplateResult): GetTemplateResult
|
||||
private respectCache (filepath: string, resolver: () => Promise<GetTemplateResult>): Promise<GetTemplateResult>
|
||||
private respectCache (filepath: string, resolver: () => GetTemplateResult | Promise<GetTemplateResult>): GetTemplateResult | Promise<GetTemplateResult> {
|
||||
if (!this.options.cache) return resolver()
|
||||
if (this.cache[filepath]) return this.cache[filepath]
|
||||
const tpl = resolver()
|
||||
if (tpl instanceof Promise) {
|
||||
return tpl.then(c => this.setCache(filepath, c))
|
||||
}
|
||||
return this.setCache(filepath, tpl)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
export class Emitter {
|
||||
public html: string = '';
|
||||
public html = '';
|
||||
public break = false;
|
||||
public continue = false;
|
||||
|
||||
public write (html: string) {
|
||||
this.html += html
|
||||
|
||||
+38
-21
@@ -1,38 +1,55 @@
|
||||
import { assert } from '../util/assert'
|
||||
import { isRange, rangeValue } from './range'
|
||||
import { isRange, rangeValue, rangeValueSync } from './range'
|
||||
import { Value } from './value'
|
||||
import { Context } from '../context/context'
|
||||
import { toValue } from '../util/underscore'
|
||||
import { isOperator, precedence, operatorImpls } from './operator'
|
||||
|
||||
export class Expression {
|
||||
private str: string
|
||||
private operands: any[] = []
|
||||
private postfix: string[]
|
||||
|
||||
public constructor (str: string = '') {
|
||||
this.str = str
|
||||
public constructor (str = '') {
|
||||
this.postfix = [...toPostfix(str)]
|
||||
}
|
||||
public evaluate (ctx: Context): any {
|
||||
public async evaluate (ctx: Context): Promise<any> {
|
||||
assert(ctx, 'unable to evaluate: context not defined')
|
||||
|
||||
const operands = []
|
||||
for (const token of toPostfix(this.str)) {
|
||||
for (const token of this.postfix) {
|
||||
if (isOperator(token)) {
|
||||
const r = operands.pop()
|
||||
const l = operands.pop()
|
||||
const result = operatorImpls[token](l, r)
|
||||
operands.push(result)
|
||||
continue
|
||||
}
|
||||
if (isRange(token)) {
|
||||
operands.push(rangeValue(token, ctx))
|
||||
continue
|
||||
}
|
||||
operands.push(new Value(token).evaluate(ctx))
|
||||
this.evaluateOnce(token)
|
||||
} else if (isRange(token)) {
|
||||
this.operands.push(await rangeValue(token, ctx))
|
||||
} else this.operands.push(await new Value(token).evaluate(ctx))
|
||||
}
|
||||
return operands[0]
|
||||
return this.operands[0]
|
||||
}
|
||||
public value (ctx: Context): any {
|
||||
return toValue(this.evaluate(ctx))
|
||||
public evaluateSync (ctx: Context): any {
|
||||
assert(ctx, 'unable to evaluate: context not defined')
|
||||
|
||||
for (const token of this.postfix) {
|
||||
if (isOperator(token)) {
|
||||
this.evaluateOnce(token)
|
||||
} else if (isRange(token)) {
|
||||
this.operands.push(rangeValueSync(token, ctx))
|
||||
} else {
|
||||
const val = new Value(token).evaluateSync(ctx)
|
||||
this.operands.push(val)
|
||||
}
|
||||
}
|
||||
return this.operands[0]
|
||||
}
|
||||
public async value (ctx: Context): Promise<any> {
|
||||
return toValue(await this.evaluate(ctx))
|
||||
}
|
||||
public valueSync (ctx: Context): any {
|
||||
return toValue(this.evaluateSync(ctx))
|
||||
}
|
||||
private evaluateOnce (token: string) {
|
||||
const r = this.operands.pop()
|
||||
const l = this.operands.pop()
|
||||
const result = operatorImpls[token](l, r)
|
||||
this.operands.push(result)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-4
@@ -3,15 +3,24 @@ import { Context } from '../context/context'
|
||||
import { range } from '../util/underscore'
|
||||
import { Value } from './value'
|
||||
|
||||
export function isRange (token: string = '') {
|
||||
export function isRange (token: string) {
|
||||
return token[0] === '(' && token[token.length - 1] === ')'
|
||||
}
|
||||
|
||||
export function rangeValue (token: string = '', ctx: Context) {
|
||||
export async function rangeValue (token: string, ctx: Context) {
|
||||
let match
|
||||
if ((match = token.match(rangeLine))) {
|
||||
const low = new Value(match[1]).value(ctx)
|
||||
const high = new Value(match[2]).value(ctx)
|
||||
const low = await new Value(match[1]).value(ctx)
|
||||
const high = await new Value(match[2]).value(ctx)
|
||||
return range(+low, +high + 1)
|
||||
}
|
||||
}
|
||||
|
||||
export function rangeValueSync (token: string, ctx: Context) {
|
||||
let match
|
||||
if ((match = token.match(rangeLine))) {
|
||||
const low = new Value(match[1]).valueSync(ctx)
|
||||
const high = new Value(match[2]).valueSync(ctx)
|
||||
return range(+low, +high + 1)
|
||||
}
|
||||
}
|
||||
|
||||
+17
-4
@@ -4,13 +4,26 @@ import { ITemplate } from '../template/itemplate'
|
||||
import { Emitter } from './emitter'
|
||||
|
||||
export class Render {
|
||||
public async renderTemplates (templates: ITemplate[], ctx: Context, emitter = new Emitter()) {
|
||||
public async renderTemplates (templates: ITemplate[], ctx: Context, emitter = new Emitter()): Promise<string> {
|
||||
for (const tpl of templates) {
|
||||
try {
|
||||
await tpl.render(ctx, emitter)
|
||||
const html = await tpl.render(ctx, emitter)
|
||||
html && emitter.write(html)
|
||||
if (emitter.break || emitter.continue) break
|
||||
} catch (e) {
|
||||
if (e.name === 'RenderBreakError') throw e
|
||||
throw e.name === 'RenderError' ? e : new RenderError(e, tpl)
|
||||
throw RenderError.is(e) ? e : new RenderError(e, tpl)
|
||||
}
|
||||
}
|
||||
return emitter.html
|
||||
}
|
||||
public renderTemplatesSync (templates: ITemplate[], ctx: Context, emitter = new Emitter()): string {
|
||||
for (const tpl of templates) {
|
||||
try {
|
||||
const html = tpl.renderSync(ctx, emitter)
|
||||
html && !(html instanceof Promise) && emitter.write(html)
|
||||
if (emitter.break || emitter.continue) break
|
||||
} catch (e) {
|
||||
throw RenderError.is(e) ? e : new RenderError(e, tpl)
|
||||
}
|
||||
}
|
||||
return emitter.html
|
||||
|
||||
+12
-4
@@ -5,11 +5,15 @@ import { parseLiteral } from '../parser/literal'
|
||||
export class Value {
|
||||
private str: string
|
||||
|
||||
public constructor (str: string = '') {
|
||||
public constructor (str: string) {
|
||||
this.str = str
|
||||
}
|
||||
|
||||
public evaluate (ctx: Context) {
|
||||
public async evaluate (ctx: Context) {
|
||||
return this.evaluateSync(ctx)
|
||||
}
|
||||
|
||||
public evaluateSync (ctx: Context) {
|
||||
const literalValue = parseLiteral(this.str)
|
||||
if (literalValue !== undefined) {
|
||||
return literalValue
|
||||
@@ -17,7 +21,11 @@ export class Value {
|
||||
return ctx.get(this.str)
|
||||
}
|
||||
|
||||
public value (ctx: Context) {
|
||||
return toValue(this.evaluate(ctx))
|
||||
public async value (ctx: Context) {
|
||||
return toValue(await this.evaluate(ctx))
|
||||
}
|
||||
|
||||
public valueSync (ctx: Context) {
|
||||
return toValue(this.evaluateSync(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,11 +21,19 @@ export class Filter {
|
||||
this.impl = impl || (x => x)
|
||||
this.args = args
|
||||
}
|
||||
public render (value: any, context: Context) {
|
||||
public async render (value: any, context: Context) {
|
||||
const argv: any[] = []
|
||||
for (const arg of this.args) {
|
||||
if (isKeyValuePair(arg)) argv.push([arg[0], new Expression(arg[1]).evaluate(context)])
|
||||
else argv.push(new Expression(arg).evaluate(context))
|
||||
if (isKeyValuePair(arg)) argv.push([arg[0], await new Expression(arg[1]).evaluate(context)])
|
||||
else argv.push(await new Expression(arg).evaluate(context))
|
||||
}
|
||||
return this.impl.apply({ context }, [value, ...argv])
|
||||
}
|
||||
public renderSync (value: any, context: Context) {
|
||||
const argv: any[] = []
|
||||
for (const arg of this.args) {
|
||||
if (isKeyValuePair(arg)) argv.push([arg[0], new Expression(arg[1]).evaluateSync(context)])
|
||||
else argv.push(new Expression(arg).evaluateSync(context))
|
||||
}
|
||||
return this.impl.apply({ context }, [value, ...argv])
|
||||
}
|
||||
|
||||
@@ -10,7 +10,10 @@ export class HTML extends Template<HTMLToken> implements ITemplate {
|
||||
super(token)
|
||||
this.str = token.value
|
||||
}
|
||||
public render (ctx: Context, emitter: Emitter) {
|
||||
public renderSync (ctx: Context, emitter: Emitter) {
|
||||
emitter.write(this.str)
|
||||
}
|
||||
public async render (ctx: Context, emitter: Emitter) {
|
||||
this.renderSync(ctx, emitter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,5 +4,6 @@ import { Emitter } from '../render/emitter'
|
||||
|
||||
export interface ITemplate {
|
||||
token: Token;
|
||||
render(ctx: Context, emitter: Emitter): Promise<void> | void;
|
||||
render(ctx: Context, emitter: Emitter): Promise<any>;
|
||||
renderSync(ctx: Context, emitter: Emitter): any;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,10 @@ export class Output extends Template<OutputToken> implements ITemplate {
|
||||
super(token)
|
||||
this.value = new Value(token.value, strictFilters)
|
||||
}
|
||||
public renderSync (ctx: Context, emitter: Emitter) {
|
||||
const val = this.value.valueSync(ctx)
|
||||
emitter.write(stringify(toValue(val)))
|
||||
}
|
||||
public async render (ctx: Context, emitter: Emitter) {
|
||||
const val = await this.value.value(ctx)
|
||||
emitter.write(stringify(toValue(val)))
|
||||
|
||||
@@ -10,14 +10,28 @@ import { Context } from '../../context/context'
|
||||
*/
|
||||
export class Hash {
|
||||
[key: string]: any
|
||||
public static async create (markup: string, ctx: Context) {
|
||||
private static parse (markup: string) {
|
||||
const instance = new Hash()
|
||||
let match
|
||||
hashCapture.lastIndex = 0
|
||||
while ((match = hashCapture.exec(markup))) {
|
||||
const k = match[1]
|
||||
const v = match[2]
|
||||
instance[k] = new Expression(v).evaluate(ctx)
|
||||
instance[k] = v
|
||||
}
|
||||
return instance
|
||||
}
|
||||
public static createSync (markup: string, ctx: Context) {
|
||||
const instance = Hash.parse(markup)
|
||||
for (const key of Object.keys(instance)) {
|
||||
instance[key] = new Expression(instance[key]).evaluateSync(ctx)
|
||||
}
|
||||
return instance
|
||||
}
|
||||
public static async create (markup: string, ctx: Context) {
|
||||
const instance = Hash.parse(markup)
|
||||
for (const key of Object.keys(instance)) {
|
||||
instance[key] = await new Expression(instance[key]).evaluate(ctx)
|
||||
}
|
||||
return instance
|
||||
}
|
||||
|
||||
@@ -8,4 +8,5 @@ import { Emitter } from '../../render/emitter'
|
||||
export interface ITagImplOptions {
|
||||
parse?: (this: ITagImpl, token: TagToken, remainingTokens: Token[]) => void;
|
||||
render: (this: ITagImpl, ctx: Context, hash: Hash, emitter: Emitter) => void;
|
||||
renderSync?: (this: ITagImpl, ctx: Context, hash: Hash, emitter: Emitter) => void;
|
||||
}
|
||||
|
||||
@@ -23,10 +23,16 @@ export class Tag extends Template<TagToken> implements ITemplate {
|
||||
this.impl.parse(token, tokens)
|
||||
}
|
||||
}
|
||||
public renderSync (ctx: Context, emitter: Emitter) {
|
||||
const hash = Hash.createSync(this.token.args, ctx)
|
||||
const impl = this.impl
|
||||
if (isFunction(impl.renderSync)) return impl.renderSync(ctx, hash, emitter)
|
||||
if (isFunction(impl.render)) return impl.render(ctx, hash, emitter)
|
||||
}
|
||||
public async render (ctx: Context, emitter: Emitter) {
|
||||
const hash = await Hash.create(this.token.args, ctx)
|
||||
const impl = this.impl
|
||||
if (isFunction(impl.render)) await impl.render(ctx, hash, emitter)
|
||||
if (isFunction(impl.render)) return impl.render(ctx, hash, emitter)
|
||||
}
|
||||
public static register (name: string, tag: ITagImplOptions) {
|
||||
Tag.impls[name] = tag
|
||||
|
||||
+10
-3
@@ -47,10 +47,17 @@ export class Value {
|
||||
}
|
||||
this.filters.push(new Filter(name, args, this.strictFilters))
|
||||
}
|
||||
public value (ctx: Context) {
|
||||
let val = new Expression(this.initial).evaluate(ctx)
|
||||
public async value (ctx: Context) {
|
||||
let val = await new Expression(this.initial).evaluate(ctx)
|
||||
for (const filter of this.filters) {
|
||||
val = filter.render(val, ctx)
|
||||
val = await filter.render(val, ctx)
|
||||
}
|
||||
return val
|
||||
}
|
||||
public valueSync (ctx: Context) {
|
||||
let val = new Expression(this.initial).evaluateSync(ctx)
|
||||
for (const filter of this.filters) {
|
||||
val = filter.renderSync(val, ctx)
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
export { ParseError, TokenizationError, RenderBreakError, AssertionError } from './util/error'
|
||||
export { ParseError, TokenizationError, AssertionError } from './util/error'
|
||||
export { Drop } from './drop/drop'
|
||||
export { Emitter } from './render/emitter'
|
||||
export { Expression } from './render/expression'
|
||||
|
||||
+2
-8
@@ -43,14 +43,8 @@ export class RenderError extends LiquidError {
|
||||
this.message = err.message
|
||||
super.update()
|
||||
}
|
||||
}
|
||||
|
||||
export class RenderBreakError extends Error {
|
||||
public resolvedHTML: string = ''
|
||||
public constructor (message: string) {
|
||||
super(message)
|
||||
this.name = 'RenderBreakError'
|
||||
this.message = message + ''
|
||||
public static is (obj: any): obj is RenderError {
|
||||
return obj instanceof RenderError
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user