forked from simon-dt/gulp-twig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·91 lines (74 loc) · 2.27 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
var map = require('map-stream');
var rext = require('replace-ext');
var gutil = require('gulp-util');
const PLUGIN_NAME = 'gulp-twig';
module.exports = function (options) {
'use strict';
if (!options) {
options = {};
}
function modifyContents(file, cb) {
var data = file.data || options.data || {};
if (file.isNull()) {
return cb(null, file);
}
if (file.isStream()) {
return cb(new gutil.PluginError(PLUGIN_NAME, "Streaming not supported!"));
}
data._file = file;
data._target = {
path: rext(file.path, '.html'),
relative: rext(file.relative, '.html')
};
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.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;
}
template = twig(twigOpts);
try {
file.contents = new Buffer(template.render(data));
}catch(e){
if (options.errorLogToConsole) {
gutil.log(PLUGIN_NAME + ' ' + e);
return cb();
}
if (typeof options.onError === 'function') {
options.onError(e);
return cb();
}
return cb(new gutil.PluginError(PLUGIN_NAME, e));
}
file.path = rext(file.path, '.html');
cb(null, file);
}
return map(modifyContents);
};