feat: pass context to filters

This commit is contained in:
harttle
2019-04-17 10:24:55 +08:00
parent 6fb4796202
commit 00bc1efe6a
15 changed files with 77 additions and 85 deletions
@@ -0,0 +1,3 @@
import { FilterImpl } from "./filter-impl";
export type FilterImplOptions = (this: FilterImpl, value: any, ...args: any[]) => any
+5 -1
View File
@@ -1 +1,5 @@
export type FilterImpl = (value: any, ...args: any[]) => any
import Context from "../../context/context";
export interface FilterImpl {
context: Context
}
+8 -8
View File
@@ -1,15 +1,15 @@
import { evalValue } from '../../render/syntax'
import Context from '../../context/context'
import { isArray } from '../../util/underscore'
import { FilterImpl } from './filter-impl'
import { FilterImplOptions } from './filter-impl-options'
export type FilterArgs = Array<string|[string?, string?]>
export class Filter {
name: string
impl: FilterImpl
impl: FilterImplOptions
args: FilterArgs
private static impls: {[key: string]: FilterImpl} = {}
private static impls: {[key: string]: FilterImplOptions} = {}
constructor (name: string, args: FilterArgs, strictFilters: boolean) {
const impl = Filter.impls[name]
@@ -19,15 +19,15 @@ export class Filter {
this.impl = impl || (x => x)
this.args = args
}
async render (value: any, ctx: Context) {
async render (value: any, context: Context) {
const argv: any[] = []
for (const arg of this.args) {
if (isArray(arg)) argv.push([arg[0], await evalValue(arg[1], ctx)])
else argv.push(await evalValue(arg, ctx))
if (isArray(arg)) argv.push([arg[0], await evalValue(arg[1], context)])
else argv.push(await evalValue(arg, context))
}
return this.impl.apply(null, [value, ...argv])
return this.impl.apply({ context }, [value, ...argv])
}
static register (name: string, filter: FilterImpl) {
static register (name: string, filter: FilterImplOptions) {
Filter.impls[name] = filter
}
static clear () {