forked from LookThink/twigjs-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
168 lines (132 loc) · 4.03 KB
/
index.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
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
'use strict';
const path = require('path');
const Twig = require('twig');
const utils = require('loader-utils');
module.exports = twigLoader;
module.exports.default = module.exports;
Twig.cache(false);
function twigLoader(source) {
const callback = this.async();
const options = utils.getOptions(this) || {};
const namespaces = options.namespaces || {};
let stringOptions = {};
if (options.functions) {
stringOptions.functions = {};
Object.entries(options.functions).forEach(([name, fn]) => {
stringOptions.functions[name] = `Twig.extendFunction('${name}', ${String(fn)});`;
return Twig.extendFunction(name, fn);
});
}
const template = Twig.twig({
allowInlineIncludes: true,
data: source,
id: makeTemplateId(this, this.resourcePath),
path: this.resourcePath,
rethrow: true,
namespaces: namespaces
});
compile(this, template, stringOptions)
.then(output => callback(null, output))
.catch(err => callback(err));
}
async function compile(loaderApi, template, options) {
let dependencies = [];
await each(template.tokens, processToken);
const opts = utils.getOptions(loaderApi) || {};
//console.log(opts)
const twigData = {
allowInlineIncludes: true,
data: template.tokens,
id: template.id,
namespaces: opts.namespaces
};
const dependenciesString = unique(dependencies)
.map(d => `require(${JSON.stringify(d)});`)
.join('\n');
let functions = '';
Object.entries(options.functions).forEach(function(entry) {
functions += entry[1];
return;
});
// console.log( twigData)
return `
${dependenciesString}
var Twig = require("twig");
${functions}
var tpl = Twig.twig(${JSON.stringify(twigData)});
module.exports = function(context) { return tpl.render(context); };
module.exports.id = ${JSON.stringify(template.id)};
module.exports.default = module.exports;
`.replace(/^\s+/gm, '');
async function processDependency(token) {
const absolutePath = await resolveModule(loaderApi, token.value);
dependencies.push(token.value);
token.value = makeTemplateId(loaderApi, absolutePath);
loaderApi.addDependency(absolutePath);
}
async function processToken(token) {
if (token.type !== 'logic' || !token.token.type) {
return;
}
switch (token.token.type) {
case 'Twig.logic.type.block':
case 'Twig.logic.type.if':
case 'Twig.logic.type.elseif':
case 'Twig.logic.type.else':
case 'Twig.logic.type.for':
case 'Twig.logic.type.spaceless':
case 'Twig.logic.type.macro': {
await each(token.token.output, processToken);
break;
}
case 'Twig.logic.type.extends':
case 'Twig.logic.type.include': {
await each(token.token.stack, processDependency);
break;
}
case 'Twig.logic.type.embed': {
await each(token.token.output, processToken);
await each(token.token.stack, processDependency);
break;
}
case 'Twig.logic.type.import':
case 'Twig.logic.type.from':
if (token.token.expression !== '_self') {
await each(token.token.stack, processDependency);
}
break;
}
}
}
async function each(arr, callback) {
if (!Array.isArray(arr)) {
return Promise.resolve();
}
return Promise.all(arr.map(callback));
}
function makeTemplateId(loaderApi, absolutePath) {
const root = loaderApi.rootContext || process.cwd();
return path.relative(root, absolutePath);
}
async function resolveModule(loaderApi, modulePath) {
return new Promise((resolve, reject) => {
loaderApi.resolve(loaderApi.context, modulePath, (err, result) => {
err ? reject(err) : resolve(result);
});
});
}
function unique(arr) {
return arr.filter((val, i, self) => self.indexOf(val) === i);
}
/**
* Render compiled twig template
*/
/*
function ExpressView(view) {
this.render = (options, callback) => {
const variables = { ...options._locals, ...options };
callback(null, view(variables));
};
this.path = view.id;
}
*/