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 | var _ = require("lodash");
|
15 | var async = require("async");
|
16 |
|
17 | grunt.registerMultiTask("dusthtml", "Render Dust templates against a context to produce HTML", function() {
|
18 | var dust;
|
19 | var done = this.async();
|
20 | var opts = this.options({
|
21 | basePath: ".",
|
22 | defaultExt: ".dust",
|
23 | whitespace: false,
|
24 | module: "dustjs-linkedin",
|
25 | context: {}
|
26 | });
|
27 |
|
28 |
|
29 | try {
|
30 | dust = require(opts.module);
|
31 | } catch(err) {
|
32 | grunt.fail.fatal("Unable to find the " + opts.module + " dependency. Did you npm install it?");
|
33 | }
|
34 |
|
35 |
|
36 | dust.onLoad = function(filePath, callback) {
|
37 |
|
38 | if(!path.extname(filePath).length) {
|
39 | filePath += opts.defaultExt;
|
40 | }
|
41 |
|
42 | if(filePath.charAt(0) !== "/") {
|
43 | filePath = opts.basePath + "/" + filePath;
|
44 | }
|
45 |
|
46 | fs.readFile(filePath, "utf8", function(err, html) {
|
47 | if(err) {
|
48 | grunt.warn("Template " + err.path + " does not exist");
|
49 | return callback(err);
|
50 | }
|
51 |
|
52 | try {
|
53 | callback(null, html);
|
54 | } catch(err) {
|
55 | parseError(err, filePath);
|
56 | }
|
57 | });
|
58 | };
|
59 |
|
60 | async.each(this.files, function(f) {
|
61 | f.src.forEach(function(srcFile) {
|
62 | var context = opts.context;
|
63 | var tmpl;
|
64 |
|
65 |
|
66 | if(opts.whitespace) {
|
67 | dust.optimizers.format = function(ctx, node) {
|
68 | return node;
|
69 | };
|
70 | }
|
71 |
|
72 |
|
73 | try {
|
74 | tmpl = dust.compileFn(grunt.file.read(srcFile));
|
75 | } catch(err) {
|
76 | parseError(err, srcFile);
|
77 | }
|
78 |
|
79 |
|
80 | if(typeof opts.context === "string") {
|
81 | context = grunt.file.readJSON(opts.context);
|
82 |
|
83 |
|
84 | } else if(Array.isArray(opts.context)) {
|
85 | context = {};
|
86 |
|
87 | opts.context.forEach(function(obj) {
|
88 | if(typeof obj === "string") {
|
89 | obj = grunt.file.readJSON(obj);
|
90 | }
|
91 |
|
92 | _.extend(context, obj);
|
93 | });
|
94 | }
|
95 |
|
96 |
|
97 | tmpl(context, function(err, html) {
|
98 | grunt.file.write(f.dest, html);
|
99 | grunt.log.writeln('File "' + f.dest + '" created.');
|
100 | });
|
101 | });
|
102 | }, done);
|
103 | });
|
104 |
|
105 | function parseError(err, filePath) {
|
106 | grunt.fatal("Error parsing dust template: " + err + " " + filePath);
|
107 | }
|
108 |
|
109 | };
|