UNPKG

1.86 kBJavaScriptView Raw
1/*
2 * grunt-nunjucks-2-html
3 * https://github.com/vitkarpov/grunt-nunjucks-2-html
4 *
5 * Copyright (c) 2014 Vit Karpov
6 * Licensed under the MIT license.
7 */
8
9var nunjucks = require('nunjucks');
10var path = require('path');
11var async = require('async');
12
13module.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 grunt.log.error(e);
49 done(err);
50 }
51
52 if (html) {
53 grunt.file.write(f.dest, html);
54 grunt.log.writeln('File "' + f.dest + '" created.');
55 done();
56 }
57
58 }, function(err) {
59 if (err) {
60 grunt.log.error(err);
61 }
62 completeTask();
63 });
64 });
65};