-
Notifications
You must be signed in to change notification settings - Fork 5
/
plugin.nunjucks-include-with.js
37 lines (31 loc) · 1.24 KB
/
plugin.nunjucks-include-with.js
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
const path = require('node:path');
const nunjucksRuntime = require('nunjucks/src/runtime');
const RELATIVE_PATTERN = /^\.{1,2}\//;
/**
* Include with tag parser
* @param {object} options - parser options
*/
function IncludeWithExtension(options) {
this.cwd = '';
this.nunjucksEnv = options.nunjucksEnv;
this.tags = [options.tagName || 'includeWith'];
this.parse = (parser, nodes) => {
const token = parser.nextToken();
const args = parser.parseSignature(null, true);
parser.advanceAfterBlockEnd(token.value);
return new nodes.CallExtension(this, 'run', args, null);
};
this.preprocess = (templateSrc, templatePath) => {
if (templatePath) {
this.cwd = path.dirname(templatePath);
}
return templateSrc;
};
this.run = (context, partialPath, data = {}, { useContext = true } = {}) => {
const fullPath = RELATIVE_PATTERN.test(partialPath) ? path.resolve(this.cwd, partialPath) : partialPath;
const mergedContext = useContext ? { ...context.ctx, ...data } : data;
const renderResult = this.nunjucksEnv.render(fullPath, mergedContext);
return new nunjucksRuntime.SafeString(renderResult);
};
}
module.exports = IncludeWithExtension;