-
Notifications
You must be signed in to change notification settings - Fork 32
/
index.js
executable file
·109 lines (91 loc) · 2.88 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
var map = require('map-stream');
var rext = require('replace-ext');
var log = require('fancy-log');
var PluginError = require('plugin-error');
const PLUGIN_NAME = 'gulp-twig';
module.exports = function (options) {
'use strict';
options = Object.assign({}, {
changeExt: true,
extname: '.html',
useFileContents: false,
}, options || {});
function modifyContents(file, cb) {
var data = file.data || Object.assign({}, options.data);
if (file.isNull()) {
return cb(null, file);
}
if (file.isStream()) {
return cb(new PluginError(PLUGIN_NAME, 'Streaming not supported!'));
}
data._file = file;
if(options.changeExt === false || options.extname === true){
data._target = {
path: file.path,
relative: file.relative
}
}else{
data._target = {
path: rext(file.path, options.extname || ''),
relative: rext(file.relative, options.extname || '')
}
}
var Twig = require('twig'),
twig = Twig.twig,
twigOpts = {
path: file.path,
async: false
},
template;
if (options.debug !== undefined) {
twigOpts.debug = options.debug;
}
if (options.trace !== undefined) {
twigOpts.trace = options.trace;
}
if (options.base !== undefined) {
twigOpts.base = options.base;
}
if (options.namespaces !== undefined) {
twigOpts.namespaces = options.namespaces;
}
if (options.cache !== true) {
Twig.cache(false);
}
if (options.functions) {
options.functions.forEach(function (func) {
Twig.extendFunction(func.name, func.func);
});
}
if (options.filters) {
options.filters.forEach(function (filter) {
Twig.extendFilter(filter.name, filter.func);
});
}
if(options.extend) {
Twig.extend(options.extend);
delete options.extend;
}
if (options.useFileContents) {
var fileContents = file.contents.toString();
twigOpts.data = fileContents
}
template = twig(twigOpts);
try {
file.contents = new Buffer(template.render(data));
}catch(e){
if (options.errorLogToConsole) {
log(PLUGIN_NAME + ' ' + e);
return cb();
}
if (typeof options.onError === 'function') {
options.onError(e);
return cb();
}
return cb(new PluginError(PLUGIN_NAME, e));
}
file.path = data._target.path;
cb(null, file);
}
return map(modifyContents);
};