forked from gianlucamancini/gulp-nunjucks-html
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (53 loc) · 1.62 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
'use strict';
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var assign = require('object-assign');
var nunjucks = require('nunjucks');
var through = require('through2');
var PLUGIN_NAME = 'gulp-nunjucks-html';
function nunjucksBuild(opts) {
return through.obj(function(file, enc, cb) {
if (file.isNull()) {
return cb(null, file);
}
if (file.isStream()) {
return cb(new PluginError(PLUGIN_NAME, 'Streams are not supported'));
}
var options = assign({
autoescape: false,
locals: {},
searchPaths: []
}, opts);
var str = file.contents.toString('utf8');
var data = file.data ? file.data : {};
var fm = file.frontMatter ? file.frontMatter : {};
var context = assign({}, options.locals, data, fm);
var loader = new nunjucks.FileSystemLoader(options.searchPaths, {
watch: false,
noCache: false
});
var env = new nunjucks.Environment(loader, (function() {
var envOptions = {};
['autoescape', 'tags'].forEach(function(opt) {
if (options.hasOwnProperty(opt)) {
envOptions[opt] = options[opt];
}
});
return envOptions;
})());
if (options.setUp && typeof options.setUp === 'function') {
env = options.setUp(env);
}
env.renderString(str, context, function(err, res) {
if (err) {
return cb(new PluginError(PLUGIN_NAME, err));
}
file.contents = new Buffer(res);
if (options.ext) {
file.path = gutil.replaceExtension(file.path, opts.ext);
}
cb(null, file);
});
});
}
module.exports = nunjucksBuild;