forked from simon-dt/gulp-twig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·104 lines (87 loc) · 2.66 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
const through2 = require('through2');
const rext = require('replace-ext');
const log = require('fancy-log');
const PluginError = require('plugin-error');
const PLUGIN_NAME = 'gulp-twig';
module.exports = function(options) {
'use strict';
function modifyContents(file, encoding, callback) {
if (file.isNull()) {
return callback(null, file);
}
if (file.isStream()) {
return callback(new PluginError(PLUGIN_NAME, 'Streaming not supported!'));
}
const {
changeExt = true,
extname = '.html',
useFileContents = false,
twigParameters = {},
data: optionsData,
cache,
functions,
filters,
extend,
errorLogToConsole,
onError,
} = options || {};
const data = file.data || optionsData || {};
const target =
changeExt === false || extname === true
? {
path: file.path,
relative: file.relative,
}
: {
path: rext(file.path, extname || ''),
relative: rext(file.relative, extname || ''),
};
const Twig = require('twig');
const { twig } = Twig;
if (cache !== true) {
Twig.cache(false);
}
if (functions) {
functions.forEach(function(func) {
Twig.extendFunction(func.name, func.func);
});
}
if (filters) {
filters.forEach(function(filter) {
Twig.extendFilter(filter.name, filter.func);
});
}
if (extend) {
Twig.extend(extend);
}
const template = twig({
...twigParameters,
rethrow: true,
async: false,
path: file.path,
data: useFileContents ? file.contents.toString() : undefined,
});
try {
file.contents = new Buffer.from(
template.render({
...data,
_target: target,
_file: file,
}),
);
} catch (e) {
if (errorLogToConsole) {
log(PLUGIN_NAME + ' ' + e);
return callback();
}
if (typeof onError === 'function') {
onError(e);
return callback();
}
return callback(new PluginError(PLUGIN_NAME, e));
}
file.path = target.path;
callback(null, file);
}
return through2.obj(modifyContents);
};