diff --git a/src/environment.ts b/src/environment.ts index 6a4d747..9721781 100644 --- a/src/environment.ts +++ b/src/environment.ts @@ -21,6 +21,12 @@ export interface TemplateSync { file?: string; } +export type TokenPreprocessor = ( + env: Environment, + tokens: Token[], + path?: string, +) => Token[] | undefined; + export type Tag = ( env: Environment, code: string, @@ -49,6 +55,7 @@ export class Environment { cache = new Map(); options: Options; tags: Tag[] = []; + tokenPreprocessors: TokenPreprocessor[] = []; filters: Record = {}; utils: Record = {}; @@ -117,12 +124,22 @@ export class Environment { defaults?: Record, sync = false, ): Template | TemplateSync { - const { tokens, position, error } = tokenize(source); + const result = tokenize(source); + let { tokens } = result; + const { position, error } = result; if (error) { throw this.createError(path || "unknown", source, position, error); } + for (const tokenPreprocessor of this.tokenPreprocessors) { + const result = tokenPreprocessor(this, tokens, path); + + if (result !== undefined) { + tokens = result; + } + } + const code = this.compileTokens(tokens).join("\n"); const { dataVarname, useWith } = this.options; const constructor = new Function( @@ -155,7 +172,12 @@ export class Environment { const path = from ? this.options.loader.resolve(from, file) : file; if (!this.cache.has(path)) { - const { source, data } = await this.options.loader.load(path); + // Remove query and hash params from path before loading + const cleanPath = path + .split("?")[0] + .split("#")[0]; + + const { source, data } = await this.options.loader.load(cleanPath); const template = this.compile(source, path, data); this.cache.set(path, template);