This repository has been archived by the owner on Oct 22, 2020. It is now read-only.
forked from backflip/gulp-twig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (67 loc) · 1.69 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
'use strict';
var Twig = require('twig'),
_ = require('lodash'),
glob = require('glob'),
fs = require('fs'),
through = require('through2'),
util = require('gulp-util');
var pluginName = 'gulp-twig',
twig = Twig.twig,
includeCache = {};
module.exports = function(options) {
options = _.merge({
data: {},
includes: null,
getIncludeId: function(filePath) {
return filePath;
}
}, options || {});
Twig.cache(false);
// Register includes
if (options.includes) {
if (!_.isArray(options.includes)) {
options.includes = [options.includes];
}
options.includes.forEach(function(pattern) {
glob.sync(pattern).forEach(function(file) {
var id = options.getIncludeId(file),
changed = fs.statSync(file).mtime,
content;
// Skip registering if include has not changed since last time
if (includeCache[id] && includeCache[id].getTime() === changed.getTime()) {
return;
}
includeCache[id] = changed;
content = fs.readFileSync(file, 'utf8').toString();
twig({
id: id,
data: content
});
});
});
}
return through.obj(function(file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', new util.PluginError(pluginName, 'Streaming not supported'));
return cb();
}
var data = typeof options.data === 'function' ? options.data(file) : options.data,
template = twig({
allowInlineIncludes: true,
data: file.contents.toString()
});
try {
file.contents = new Buffer(template.render(data));
} catch(err) {
this.emit('error', new util.PluginError(pluginName, err));
return cb();
}
// Add file back to stream
this.push(file);
cb();
});
};