-
Notifications
You must be signed in to change notification settings - Fork 275
/
Copy pathtwig.loader.fs.js
81 lines (65 loc) · 2.38 KB
/
twig.loader.fs.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
module.exports = function (Twig) {
'use strict';
let fs;
let path;
try {
// Require lib dependencies at runtime
fs = require('fs');
path = require('path');
} catch (error) {
// NOTE: this is in a try/catch to avoid errors cross platform
console.warn('Missing fs and path modules. ' + error);
}
Twig.Templates.registerLoader('fs', function (location, params, callback, errorCallback) {
let template;
let data = null;
const {precompiled} = params;
const parser = this.parsers[params.parser] || this.parser.twig;
if (!fs || !path) {
throw new Twig.Error('Unsupported platform: Unable to load from file ' +
'because there is no "fs" or "path" implementation');
}
const loadTemplateFn = function (err, data) {
if (err) {
if (typeof errorCallback === 'function') {
errorCallback(err);
}
return;
}
if (precompiled === true) {
data = JSON.parse(data);
}
params.data = data;
params.path = params.path || location;
// Template is in data
template = parser.call(this, params);
if (typeof callback === 'function') {
callback(template);
}
};
params.path = params.path || location;
if (params.async) {
fs.stat(params.path, (err, stats) => {
if (err || !stats.isFile()) {
if (typeof errorCallback === 'function') {
errorCallback(new Twig.Error('Unable to find template file ' + params.path));
}
return;
}
fs.readFile(params.path, 'utf8', loadTemplateFn);
});
// TODO: return deferred promise
return true;
}
try {
if (!fs.statSync(params.path).isFile()) {
throw new Twig.Error('Unable to find template file ' + params.path);
}
} catch (error) {
throw new Twig.Error('Unable to find template file ' + params.path + '. ' + error);
}
data = fs.readFileSync(params.path, 'utf8');
loadTemplateFn(undefined, data);
return template;
});
};