UNPKG

2.47 kBJavaScriptView Raw
1/*
2 * Grunt Dust-HTML
3 * https://github.com/ehynds/grunt-dust-html
4 *
5 * Copyright (c) 2013 Eric Hynds
6 * Licensed under the MIT license.
7 */
8
9module.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 // find me some dust
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 // Load includes/partials from the filesystem properly
34 dust.onLoad = function(filePath, callback) {
35 // Make sure the file to load has the proper extension
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 // preserve whitespace?
70 if(opts.whitespace) {
71 dust.optimizers.format = function(ctx, node) {
72 return node;
73 };
74 }
75
76 // if context is a string assume it's a file location
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 // parse and save as html
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};