-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
nunjucks.ts
317 lines (267 loc) Β· 8.01 KB
/
nunjucks.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import nunjucks from "../deps/nunjucks.ts";
import loader from "../core/loaders/text.ts";
import { merge, normalizePath } from "../core/utils.ts";
import { Exception } from "../core/errors.ts";
import { join } from "../deps/path.ts";
import type {
ComponentFunction,
Data,
Engine,
Helper,
HelperOptions,
ProxyComponents,
Site,
} from "../core.ts";
import type { NunjucksOptions } from "../deps/nunjucks.ts";
export interface Options {
/** The list of extensions this plugin applies to */
extensions: string[] | {
pages: string[];
components: string[];
};
/** Custom includes path */
includes: string;
/** Options passed to Nunjucks */
options: Partial<NunjucksOptions>;
/** Plugins loaded by Nunjucks */
plugins: {
[index: string]: unknown;
};
}
// Default options
export const defaults: Options = {
extensions: [".njk"],
includes: "",
options: {},
plugins: {},
};
/** Template engine to render Nunjucks files */
export class NunjucksEngine implements Engine {
// deno-lint-ignore no-explicit-any
env: any;
cache = new Map();
basePath: string;
// deno-lint-ignore no-explicit-any
constructor(env: any, basePath: string) {
this.env = env;
this.basePath = basePath;
}
deleteCache(file: string): void {
this.cache.delete(file);
// Remove the internal cache of nunjucks
const fsLoader = this.env.loaders[0];
const filename = join(this.basePath, file);
const name = fsLoader.pathsToNames[filename];
if (name) {
delete fsLoader.cache[name];
}
}
render(content: string, data?: Data, filename?: string) {
if (!filename) {
return new Promise((resolve, reject) => {
this.env.renderString(content, data, (err: Error, result: string) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
const template = this.getTemplate(content, filename);
return new Promise((resolve, reject) => {
template.render(data, (err: unknown, result: string) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
renderSync(content: string, data?: Data, filename?: string): string {
if (!filename) {
return this.env.renderString(content, data);
}
const template = this.getTemplate(content, filename);
return template.render(data);
}
getTemplate(content: string, filename: string) {
if (!this.cache.has(filename)) {
this.cache.set(
filename,
nunjucks.compile(content, this.env, join(this.basePath, filename)),
);
}
return this.cache.get(filename)!;
}
addHelper(name: string, fn: Helper, options: HelperOptions) {
switch (options.type) {
case "tag": {
const tag = createCustomTag(name, fn, options);
this.env.addExtension(name, tag);
return;
}
case "filter":
if (options.async) {
const filter = createAsyncFilter(fn);
this.env.addFilter(name, filter, true);
return;
}
this.env.addFilter(name, fn);
}
}
}
/** Register the plugin to use Nunjucks as a template engine */
export default function (userOptions?: Partial<Options>) {
return (site: Site) => {
const options = merge(
{ ...defaults, includes: site.options.includes },
userOptions,
);
const extensions = Array.isArray(options.extensions)
? { pages: options.extensions, components: options.extensions }
: options.extensions;
// Create the nunjucks environment instance
const fsLoader = new nunjucks.FileSystemLoader(site.src(options.includes));
const basePath = site.src();
const lumeLoader = {
async: true,
async getSource(
path: string,
callback: (err?: string, src?: { src: string; path: string }) => void,
) {
let relPath = normalizePath(path);
relPath = relPath.startsWith(basePath)
? relPath.slice(basePath.length)
: relPath;
const content = await site.getContent(relPath);
if (content) {
callback(undefined, {
src: content as string,
path,
});
return;
}
callback(`Could not load ${path}`);
},
};
const env = new nunjucks.Environment(
[fsLoader, lumeLoader],
options.options,
);
for (const [name, fn] of Object.entries(options.plugins)) {
env.addExtension(name, fn);
}
const engine = new NunjucksEngine(env, site.src());
site.loadPages(extensions.pages, loader, engine);
site.includes(extensions.pages, options.includes);
site.loadComponents(extensions.components, loader, engine);
// Register the njk filter
site.filter("njk", filter as Helper, true);
// Register the component helper
engine.addHelper("comp", (...args) => {
const baseData = site.source.root!.baseData || {};
const components = baseData[site.options.components.variable] as
| ProxyComponents
| undefined;
const [content, name, options = {}] = args;
delete options.__keywords;
const props = { content, ...options };
if (!components) {
throw new Exception(`Component "${name}" not found`);
}
const names = name.split(".") as string[];
let component: ProxyComponents | ComponentFunction | undefined =
components;
while (names.length) {
try {
// @ts-ignore: `component` is defined or throw an error
component = component[names.shift()];
} catch {
throw new Exception(`Component "${name}" not found`);
}
}
if (typeof component === "function") {
return component(props);
}
throw new Exception(`Component "${name}" not found`);
}, {
type: "tag",
body: true,
});
function filter(string: string, data?: Data) {
return engine.render(string, { ...site.globalData, ...data });
}
};
}
/**
* Create an asynchronous filter
* by to adapting the Promise-based functions to callbacks used by Nunjucks
* https://mozilla.github.io/nunjucks/api.html#custom-filters
*/
function createAsyncFilter(fn: Helper) {
return async function (...args: unknown[]) {
const cb = args.pop() as (err: unknown, result?: unknown) => void;
try {
const result = await fn(...args);
cb(null, result);
} catch (err) {
cb(err);
}
};
}
/**
* Create a tag extension
* https://mozilla.github.io/nunjucks/api.html#custom-tags
*
* @param name The tag name
* @param fn The function to render this tag
* @param options The options to configure this tag
*/
function createCustomTag(name: string, fn: Helper, options: HelperOptions) {
const tagExtension = {
tags: [name],
// @ts-ignore: There's no types for Nunjucks
parse(parser, nodes) {
const token = parser.nextToken();
const args = parser.parseSignature(null, true);
parser.advanceAfterBlockEnd(token.value);
const extraArgs = [];
if (options.body) {
const body = parser.parseUntilBlocks(`end${name}`);
extraArgs.push(body);
parser.advanceAfterBlockEnd();
}
if (options.async) {
return new nodes.CallExtensionAsync(
tagExtension,
"run",
args,
extraArgs,
);
}
return new nodes.CallExtension(tagExtension, "run", args, extraArgs);
},
// @ts-ignore: There's no types for Nunjucks
run(_context: unknown, ...args) {
if (options.body) {
const [body] = args.splice(
options.async ? args.length - 2 : args.length - 1,
1,
);
args.unshift(body());
}
if (!options.async) {
const string = fn(...args);
return new nunjucks.runtime.SafeString(string);
}
const callback = args.pop();
(fn(...args) as Promise<string>).then((string: string) => {
const result = new nunjucks.runtime.SafeString(string);
callback(null, result);
});
},
};
return tagExtension;
}