forked from virtru/gulp-swig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (63 loc) · 1.8 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
var es = require('event-stream');
var swig = require('swig-templates');
var clone = require('clone');
var gutil = require('gulp-util');
var ext = gutil.replaceExtension;
var PluginError = gutil.PluginError;
var fs = require('fs');
var path = require('path');
function extend(target) {
'use strict';
var sources = [].slice.call(arguments, 1);
sources.forEach(function(source) {
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
});
return target;
}
module.exports = function(options) {
'use strict';
var opts = options ? clone(options) : {};
opts.ext = opts.ext || ".html";
if (opts.defaults) {
swig.setDefaults(opts.defaults);
}
if (opts.setup && typeof opts.setup === 'function') {
opts.setup(swig);
}
function gulpswig(file, callback) {
var data = opts.data || {}, jsonPath;
if (typeof data === 'function') {
data = data(file);
}
if (file.data) {
data = extend(file.data, data);
}
if (opts.load_json === true) {
if (opts.json_path) {
jsonPath = path.join(opts.json_path, ext(path.basename(file.path), '.json'));
} else {
jsonPath = ext(file.path, '.json');
}
// skip error if json file doesn't exist
try {
data = extend(JSON.parse(fs.readFileSync(jsonPath)), data);
} catch (err) {}
}
try {
var _swig = opts.varControls ? new swig.Swig(opts) : swig;
var tpl = _swig.compile(String(file.contents), {filename: file.path});
var compiled = tpl(data);
file.path = ext(file.path, opts.ext);
file.contents = new Buffer(compiled);
callback(null, file);
} catch (err) {
callback(new PluginError('gulp-swig', err));
callback();
}
}
return es.map(gulpswig);
};