deno.land / x / lume@v2.1.4 / plugins / 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import nunjucks from "../deps/nunjucks.ts";import loader from "../core/loaders/text.ts";import { merge } from "../core/utils/object.ts";import { normalizePath, resolveInclude } from "../core/utils/path.ts";import { basename, join, posix } from "../deps/path.ts";
import type Site from "../core/site.ts";import type { Engine, Helper, HelperOptions } from "../core/renderer.ts";import type { ProxyComponents } from "../core/source.ts";
export interface Options { /** The list of extensions this plugin applies to */ extensions?: string[];
/** Optional sub-extension for page files */ pageSubExtension?: string;
/** * Custom includes path * @default `site.options.includes` */ includes?: string;
/** * Options passed to Nunjucks * @see https://mozilla.github.io/nunjucks/api.html#configure */ options?: nunjucks.ConfigureOptions;
/** Plugins loaded by Nunjucks */ plugins?: { [index: string]: nunjucks.Extension; };}
// Default optionsexport const defaults: Options = { extensions: [".njk"], 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; includes: string;
// deno-lint-ignore no-explicit-any constructor(env: any, basePath: string, includes: string) { this.env = env; this.basePath = basePath; this.includes = includes; }
deleteCache(file: string): void { this.cache.delete(file); const filename = basename(file);
// Remove the internal cache of nunjucks // deno-lint-ignore no-explicit-any this.env.loaders.forEach((fsLoader: any) => { Object.keys(fsLoader.cache).forEach((key) => { if (key.endsWith(filename)) { delete fsLoader.cache[key]; } }); }); }
render( content: string, data?: Record<string, unknown>, filename?: string, ): Promise<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); } }); }); }
renderComponent( content: string, data?: Record<string, unknown>, 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, // @ts-ignore: The type definition of nunjucks is wrong 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; }
// deno-lint-ignore no-explicit-any this.env.addFilter(name, function (this: any, ...args: unknown[]) { return fn.apply({ data: this.ctx }, args); }); } }}
class LumeLoader extends nunjucks.Loader implements nunjucks.ILoaderAsync { includes: string;
constructor(private site: Site, includes: string) { super(); this.includes = includes; }
async: true = true;
getSource( id: string, callback: nunjucks.Callback<Error, nunjucks.LoaderSource>, ) { const rootToRemove = this.site.src(); let path = normalizePath(id, rootToRemove);
if (path === normalizePath(id)) { path = resolveInclude(id, this.includes, undefined, rootToRemove); }
this.site.getContent(path, loader).then((content) => { if (content) { callback(null, { src: content as string, path, noCache: false, }); return; }
callback(new Error(`Could not load ${path}`), null); }); }
resolve(from: string, to: string): string { return posix.join(posix.dirname(from), to); }}
/** Register the plugin to use Nunjucks as a template engine */export default function (userOptions?: Options) { return (site: Site) => { const options = merge( { ...defaults, includes: site.options.includes }, userOptions, );
const env = new nunjucks.Environment( [new LumeLoader(site, options.includes)], options.options, );
for (const [name, fn] of Object.entries(options.plugins)) { env.addExtension(name, fn); }
site.hooks.addNunjucksPlugin = (name, fn) => { env.addExtension(name, fn); };
const engine = new NunjucksEngine(env, site.src(), options.includes);
// Ignore includes folder if (options.includes) { site.ignore(options.includes); }
// Load the pages and register the engine site.loadPages(options.extensions, { loader, engine, pageSubExtension: options.pageSubExtension, });
// Register the njk filter site.filter("njk", filter, true);
// Register the component helper engine.addHelper("comp", (...args) => { const components = site.source.data.get("/") ?.[site.options.components.variable] as | ProxyComponents | undefined; const [content, name, options = {}] = args; delete options.__keywords; const props = { content, ...options };
if (!components) { throw new Error(`Component "${name}" not found`); }
const names = name.split(".") as string[]; let component: ProxyComponents | undefined = components;
while (names.length) { try { // @ts-ignore: `component` is defined or throw an error component = component[names.shift()]; } catch { throw new Error(`Component "${name}" not found`); } }
if (typeof component === "function") { return component(props); }
throw new Error(`Component "${name}" not found`); }, { type: "tag", body: true, });
function filter( string: string, data?: Record<string, unknown>, ): Promise<string> { return engine.render(string, { ...site.scopedData.get("/"), ...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) { // deno-lint-ignore no-explicit-any return async function (this: any, ...args: unknown[]) { const cb = args.pop() as (err: unknown, result?: unknown) => void;
try { const result = await fn.apply({ data: this.ctx }, 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); },
// deno-lint-ignore no-explicit-any run(context: any, ...args: any[]) { 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.apply({ data: context.ctx }, args); return new nunjucks.runtime.SafeString(string); }
const callback = args.pop();
(fn.apply({ data: context.ctx }, args) as Promise<string>).then( (string: string) => { const result = new nunjucks.runtime.SafeString(string); callback(null, result); }, ); }, };
return tagExtension;}
/** Extends Helpers interface */declare global { namespace Lume { export interface Helpers { /** @see https://lume.land/plugins/nunjucks/ */ njk: (string: string, data?: Record<string, unknown>) => Promise<string>; } }}
lume

Version Info

Tagged at
7 months ago