1 | 'use strict';
|
2 |
|
3 | var gutil = require('gulp-util');
|
4 | var PluginError = gutil.PluginError;
|
5 |
|
6 | var assign = require('object-assign');
|
7 | var nunjucks = require('nunjucks');
|
8 | var through = require('through2');
|
9 |
|
10 | function nunjucksBuild(opts) {
|
11 |
|
12 | return through.obj(function(file, enc, cb) {
|
13 |
|
14 | if (file.isNull()) {
|
15 | return cb(null, file);
|
16 | }
|
17 |
|
18 | if (file.isStream()) {
|
19 | return cb(new PluginError('gulp-nunjucks-html', 'Streams are not supported'));
|
20 | }
|
21 |
|
22 | var options = assign({
|
23 | autoescape: false,
|
24 | locals: {},
|
25 | searchPaths: []
|
26 | }, opts);
|
27 |
|
28 | var str = file.contents.toString('utf8');
|
29 | var data;
|
30 |
|
31 | if (file.data) {
|
32 | data = assign(options.locals, file.data);
|
33 | } else {
|
34 | data = options.locals;
|
35 | }
|
36 |
|
37 | var loader = new nunjucks.FileSystemLoader(options.searchPaths, {
|
38 | autoescape: options.autoescape
|
39 | });
|
40 | var env = new nunjucks.Environment(loader);
|
41 |
|
42 | if (options.setUp && typeof options.setUp === 'function') {
|
43 | env = options.setUp(env);
|
44 | }
|
45 |
|
46 | env.renderString(str, data, function(err, res) {
|
47 |
|
48 | if (err) {
|
49 | return cb(new PluginError('gulp-nunjucks-html', err));
|
50 | }
|
51 |
|
52 | file.contents = new Buffer(res);
|
53 |
|
54 | cb(null, file);
|
55 |
|
56 | });
|
57 |
|
58 | });
|
59 |
|
60 | }
|
61 |
|
62 | module.exports = nunjucksBuild;
|