UNPKG

2.9 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 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", // dust, dustjs-helpers, or dustjs-linkedin
25 context: {}
26 });
27
28 // Require dust
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 // Load includes/partials from the filesystem properly
36 dust.onLoad = function(filePath, callback) {
37 // Make sure the file to load has the proper extension
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 // preserve whitespace?
66 if(opts.whitespace) {
67 dust.optimizers.format = function(ctx, node) {
68 return node;
69 };
70 }
71
72 // pre-compile the template
73 try {
74 tmpl = dust.compileFn(grunt.file.read(srcFile));
75 } catch(err) {
76 parseError(err, srcFile);
77 }
78
79 // if context is a string assume it's the location to a file
80 if(typeof opts.context === "string") {
81 context = grunt.file.readJSON(opts.context);
82
83 // if context is an array merge each item together
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 // render template and save as html
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};