-
Notifications
You must be signed in to change notification settings - Fork 33
/
index.js
84 lines (70 loc) · 2.05 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
'use strict';
var _ = require('lodash');
var PluginError = require('plugin-error');
var replaceExtension = require('replace-ext');
var through = require('through2');
var nunjucks = require('nunjucks');
var defaults = {
path: '.',
ext: '.html',
data: {},
inheritExtension: false,
envOptions: {
watch: false
},
manageEnv: null
};
module.exports = function (options) {
options = _.defaultsDeep(options || {}, defaults);
nunjucks.configure(options.envOptions);
if (!options.loaders) {
options.loaders = new nunjucks.FileSystemLoader(options.path);
}
var compile = new nunjucks.Environment(options.loaders, options.envOptions);
if (_.isFunction(options.manageEnv)) {
options.manageEnv.call(null, compile);
}
/*
* file = file
* cb = callback function
*/
return through.obj(function(file, enc, cb) {
var data = _.cloneDeep(options.data);
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.data) {
data = _.merge(file.data, data);
}
if (file.isStream()) {
this.emit('error', new PluginError('gulp-nunjucks', 'Streaming not supported'));
return cb();
}
var _this = this;
var filePath = file.path;
try {
compile.renderString(file.contents.toString(), data, function (err, result) {
if (err) {
_this.emit('error', new PluginError('gulp-nunjucks', err, {fileName: filePath}));
return cb();
}
file.contents = Buffer.from(result);
// Replace extension with mentioned/default extension
// only if inherit extension flag is not provided(truthy)
if (!options.inheritExtension) {
file.path = replaceExtension(filePath, options.ext);
}
_this.push(file);
cb();
});
} catch (err) {
_this.emit('error', new PluginError('gulp-nunjucks', err, {fileName: filePath}));
cb();
}
});
};
module.exports.setDefaults = function (options) {
defaults = _.defaultsDeep(options || {}, defaults);
};
module.exports.nunjucks = nunjucks;