feat: globals shared between tags, see #185

This commit is contained in:
harttle
2020-02-08 04:59:23 +08:00
parent fc0cf6fe7b
commit 870e7ec6aa
4 changed files with 29 additions and 9 deletions
+9 -6
View File
@@ -1,7 +1,7 @@
import { Drop } from '../drop/drop'
import { __assign } from 'tslib'
import { assert } from '../util/assert'
import { NormalizedFullOptions, applyDefault } from '../liquid-options'
import { NormalizedFullOptions, defaultOptions } from '../liquid-options'
import { Scope } from './scope'
import { isArray, isNil, isString, isFunction, toLiquid } from '../util/underscore'
@@ -9,11 +9,13 @@ export class Context {
private scopes: Scope[] = [{}]
private registers = {}
public environments: Scope
public globals: Scope
public sync: boolean
public opts: NormalizedFullOptions
public constructor (env: object = {}, opts?: NormalizedFullOptions, sync = false) {
public constructor (env: object = {}, opts: NormalizedFullOptions = defaultOptions, sync = false) {
this.sync = sync
this.opts = applyDefault(opts)
this.opts = opts
this.globals = opts.globals
this.environments = env
}
public getRegister (key: string, defaultValue = {}) {
@@ -23,12 +25,12 @@ export class Context {
return (this.registers[key] = value)
}
public getAll () {
return [this.environments, ...this.scopes]
return [this.globals, this.environments, ...this.scopes]
.reduce((ctx, val) => __assign(ctx, val), {})
}
public get (path: string) {
const paths = this.parseProp(path)
const scope = this.findScope(paths[0]) || this.environments
const scope = this.findScope(paths[0])
return this.getFromScope(scope, paths)
}
public getFromScope (scope: object, paths: string[] | string) {
@@ -57,7 +59,8 @@ export class Context {
return candidate
}
}
return null
if (key in this.environments) return this.environments
return this.globals
}
/*
+6 -2
View File
@@ -34,6 +34,8 @@ export interface LiquidOptions {
greedy?: boolean;
/** `fs` is used to override the default file-system module with a custom implementation. */
fs?: IFS;
/** the global environment passed down to all partial templates, i.e. templates included by `include`, `layout` and `render` tags. */
globals?: object;
}
interface NormalizedOptions extends LiquidOptions {
@@ -56,9 +58,10 @@ export interface NormalizedFullOptions extends NormalizedOptions {
outputDelimiterLeft: string;
outputDelimiterRight: string;
greedy: boolean;
globals: object;
}
const defaultOptions: NormalizedFullOptions = {
export const defaultOptions: NormalizedFullOptions = {
root: ['.'],
cache: false,
extname: '',
@@ -73,7 +76,8 @@ const defaultOptions: NormalizedFullOptions = {
outputDelimiterLeft: '{{',
outputDelimiterRight: '}}',
strictFilters: false,
strictVariables: false
strictVariables: false,
globals: {}
}
export function normalize (options?: LiquidOptions): NormalizedOptions {