1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | module.exports = function(grunt) {
|
10 | "use strict";
|
11 |
|
12 | var path = require("path");
|
13 | var fs = require("fs");
|
14 |
|
15 | grunt.registerMultiTask("dusthtml", "Render Dust templates against a context to produce HTML", function() {
|
16 | var dust;
|
17 |
|
18 |
|
19 | try {
|
20 | dust = require("dust");
|
21 | } catch(err) {
|
22 | dust = require("dustjs-linkedin");
|
23 | }
|
24 |
|
25 | var done = this.async();
|
26 | var opts = this.options({
|
27 | basePath: ".",
|
28 | defaultExt: ".dust",
|
29 | whitespace: false,
|
30 | context: {}
|
31 | });
|
32 |
|
33 |
|
34 | dust.onLoad = function(filePath, callback) {
|
35 |
|
36 | if(!path.extname(filePath).length) {
|
37 | filePath += opts.defaultExt;
|
38 | }
|
39 |
|
40 | if(filePath.charAt(0) !== "/") {
|
41 | filePath = opts.basePath + "/" + filePath;
|
42 | }
|
43 |
|
44 | fs.readFile(filePath, "utf8", function(err, html) {
|
45 | if(err) {
|
46 | grunt.warn("Template " + err.path + " does not exist");
|
47 | return callback(err);
|
48 | }
|
49 |
|
50 | try {
|
51 | callback(null, html);
|
52 | } catch(err) {
|
53 | parseError(err, filePath);
|
54 | }
|
55 | });
|
56 | };
|
57 |
|
58 | this.files.forEach(function(f) {
|
59 | f.src.forEach(function(srcFile) {
|
60 | var context = opts.context;
|
61 | var tmpl;
|
62 |
|
63 | try {
|
64 | tmpl = dust.compileFn(grunt.file.read(srcFile));
|
65 | } catch(err) {
|
66 | parseError(err, srcFile);
|
67 | }
|
68 |
|
69 |
|
70 | if(opts.whitespace) {
|
71 | dust.optimizers.format = function(ctx, node) {
|
72 | return node;
|
73 | };
|
74 | }
|
75 |
|
76 |
|
77 | if(typeof opts.context === "string") {
|
78 | try {
|
79 | context = grunt.file.readJSON(opts.context);
|
80 | } catch(e) {
|
81 | grunt.fatal("An error occurred parsing " + opts.context + ". Is it valid JSON?");
|
82 | }
|
83 | }
|
84 |
|
85 |
|
86 | tmpl(context, function(err, html) {
|
87 | grunt.file.write(f.dest, html);
|
88 | grunt.log.writeln('File "' + f.dest + '" created.');
|
89 | done();
|
90 | });
|
91 | });
|
92 | });
|
93 | });
|
94 |
|
95 | function parseError(err, filePath) {
|
96 | grunt.fatal("Error parsing dust template: " + err + " " + filePath);
|
97 | }
|
98 |
|
99 | };
|