/
engine.ts
116 lines (101 loc) 路 2.64 KB
/
engine.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import {
ALL,
App,
Config,
Init,
Provide,
Scope,
ScopeEnum,
} from '@midwayjs/core';
import {
ConfigureOptions,
Environment,
FileSystemLoader,
ILoader,
runtime,
TemplateCallback,
} from 'nunjucks';
import { RenderOptions } from '@midwayjs/view';
class MidwayNunjucksEnvironment extends Environment {
constructor(
fileLoader?: ILoader | ILoader[] | null,
config?: ConfigureOptions
) {
super(fileLoader, config);
// http://disse.cting.org/2016/08/02/2016-08-02-sandbox-break-out-nunjucks-template-engine
const originMemberLookup = runtime.memberLookup;
runtime.memberLookup = function (...args: unknown[]) {
const val = args[1];
if (val === 'prototype' || val === 'constructor') return null;
return originMemberLookup(...args);
};
}
}
@Provide()
@Scope(ScopeEnum.Singleton)
export class NunjucksEnvironment {
protected nunjucksEnvironment: Environment;
@App()
protected app;
@Config(ALL)
protected globalConfig;
@Init()
protected async init() {
const coreLogger = this.app.getCoreLogger();
const viewPaths = this.globalConfig.view.root;
coreLogger.info(
'[midway:view-nunjucks] loading templates from %j',
viewPaths
);
const config = this.globalConfig['nunjucks'];
config.noCache = !config.cache;
delete config.cache;
const nunjucksConfig = {
noCache: config.noCache,
throwOnUndefined: config.throwOnUndefined,
trimBlocks: config.trimBlocks,
lstripBlocks: config.lstripBlocks,
tags: config.tags,
autoescape: config.autoescape,
};
const fileLoader = new FileSystemLoader(this.globalConfig.view.root, {
noCache: nunjucksConfig.noCache,
});
this.nunjucksEnvironment = new MidwayNunjucksEnvironment(
fileLoader,
nunjucksConfig
);
}
render(
name: string,
context?: Record<string, any>,
callback?: TemplateCallback<string>
) {
return this.nunjucksEnvironment.render(name, context, callback);
}
renderString(
tpl: string,
context?: Record<string, any>,
options?: RenderOptions,
callback?: TemplateCallback<string>
) {
return this.nunjucksEnvironment.renderString(
tpl,
context,
options,
callback
);
}
addFilter(name: string, callback: (...args) => string) {
return this.nunjucksEnvironment.addFilter(name, callback);
}
getFilter(name: string) {
return this.nunjucksEnvironment.getFilter(name);
}
hasExtension(name: string): boolean {
return this.nunjucksEnvironment.hasExtension(name);
}
addGlobal(name: string, value) {
return this.nunjucksEnvironment.addGlobal(name, value);
}
}