1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | var nunjucks = require('nunjucks');
|
10 | var path = require('path');
|
11 | var async = require('async');
|
12 |
|
13 | module.exports = function(grunt) {
|
14 | 'use strict';
|
15 |
|
16 | grunt.registerMultiTask('nunjucks', 'Renders nunjucks` template to HTML', function() {
|
17 | var options = this.options();
|
18 | var completeTask = this.async();
|
19 |
|
20 | if (!options.data) {
|
21 | grunt.log.warn('Template`s data is empty. Guess you forget to specify data option');
|
22 | }
|
23 |
|
24 | var envOptions = { watch: false };
|
25 | if (options.tags) {
|
26 | envOptions.tags = options.tags;
|
27 | }
|
28 |
|
29 | var basePath = options.paths || '';
|
30 | var env = nunjucks.configure(basePath, envOptions);
|
31 |
|
32 | if (typeof options.configureEnvironment === 'function') {
|
33 | options.configureEnvironment(env);
|
34 | }
|
35 |
|
36 | async.each(this.files, function(f, done) {
|
37 | var filepath = path.join(process.cwd(), f.src[0]);
|
38 | var data = JSON.parse(JSON.stringify(options.data || {}));
|
39 |
|
40 | if (typeof options.preprocessData === 'function') {
|
41 | data = options.preprocessData.call(f, data);
|
42 | }
|
43 |
|
44 | var template = grunt.file.read(filepath);
|
45 | try {
|
46 | var html = env.renderString(template, data);
|
47 | } catch(e) {
|
48 | done(e);
|
49 | }
|
50 |
|
51 | if (html) {
|
52 | grunt.file.write(f.dest, html);
|
53 | grunt.log.writeln('File "' + f.dest + '" created.');
|
54 | done();
|
55 | }
|
56 |
|
57 | }, function(err) {
|
58 | if (err) {
|
59 | grunt.log.error(err);
|
60 | }
|
61 | completeTask();
|
62 | });
|
63 | });
|
64 | };
|