/
handlebars.js
190 lines (159 loc) · 6.46 KB
/
handlebars.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
/*
* grunt-handlebars-compiler
* https://github.com/mattacular/grunt-handlebars-compiler
*
* Copyright (c) 2013 mstills
* Licensed under the MIT license.
*/
module.exports = function (grunt) {
'use strict';
var _ = grunt.util._,
uglify = require('uglify-js'),
defaultProcessFilename;
// filename conversion for templates and partials
defaultProcessFilename = function (filePath) {
var pieces = _.last(filePath.split('/')).split('.'), // strips off path and gets the filename
name = _(pieces).without(_.last(pieces)).join('-'); // strips file extension
return name;
};
// the 'handlebars' task
grunt.registerMultiTask('handlebars', 'Compile *.handlebars templates with given options.', function () {
var options = this.options({
separator: grunt.util.linefeed,
namespace: 'Handlebars.templates',
exportAMD: false,
exportCommonJS: false,
pathToHandlebars: '', // only relevant to 'exportAMD: true' - amd style option
returnAMD: false, // only relevant to 'exportAMD: true' - return the module directly for use
knownHelpers: [], // provide an array of known helpers
knownOnly: false, // compile known helpers only
templateRoot: false, // base value to strip from template names
partial: false, // specify that templates are partials
min: false, // minify output
compress: false, // experimental: compress whitespace (by prepending {{!~}} to each indented line)
returnTemplates: false // return templates
}),
compilerOptions = {},
known = {},
knownLabel = '',
processFilename,
prefix, midfix, wrapOpen, wrapClose, suffix;
grunt.verbose.writeflags(options, 'Options');
// check for valid knownHelpers option
if (!Array.isArray(options.knownHelpers)) {
options.knownHelpers = [];
} else {
compilerOptions.knownHelpers = options.knownHelpers;
}
// decide template prefix & suffix
if (options.exportAMD && options.exportCommonJS) {
grunt.fail.warn('Cannot choose to compile as both an AMD and a CommonJS module. Please remove either the \'exportAMD\' or \'exportCommonJS\' option from your Gruntfile.js.');
} else if (options.exportAMD) {
prefix = 'define([\'' + (options.pathToHandlebars || 'handlebars') + '\'], function (Handlebars) {\n';
grunt.log.writeln('Compiling as AMD/RequireJS module(s).');
suffix = options.returnTemplates ? 'return templates;\n});' : '});';
} else if (options.exportCommonJS) {
if (typeof options.exportCommonJS !== 'string') {
grunt.fail.warn('Must provide a path to Handlebars module in order to compile as a CommonJS module.');
}
grunt.log.writeln('Compiling as Common JS module(s).');
prefix = 'var Handlebars = require(\'' + options.exportCommonJS + '\');\n';
suffix = options.returnTemplates ? 'module.exports = templates;' : '';
} else {
prefix = '(function() {\n';
suffix = options.returnTemplates ? 'return templates;\n}());' : '}());';
}
// decide template midfix
midfix = 'var template = Handlebars.template, templates = ' + (options.namespace ? options.namespace + ' = ' + options.namespace + ' || {}' : '{}') + ';\n';
// assign filename processing (this decides template name under namespace)
processFilename = options.processFilename || defaultProcessFilename;
// convert known helpers array/list to an object literal
if (options.knownHelpers && !Array.isArray(options.knownHelpers)) {
options.knownHelpers = [options.knownHelpers];
}
if (options.knownHelpers && options.knownHelpers.length > 0) {
for (var i = 0; i < options.knownHelpers.length; i += 1) {
known[options.knownHelpers[i]] = true;
knownLabel += (i !== options.knownHelpers.length - 1) ? options.knownHelpers[i] + ', ' : options.knownHelpers[i];
}
grunt.log.writeln('Compiling with known helpers: ');
grunt.log.ok(knownLabel);
compilerOptions = {
'knownHelpers': known,
'knownHelpersOnly': options.knownOnly
};
}
this.files.forEach(function (f) {
var partials = [],
templates = [],
output;
// iterate files, processing partials and templates separately
f.src.filter(function (filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
})
.forEach(function (filepath) {
var src = grunt.file.read(filepath),
compiled, filename;
filepath = filepath.split('/');
filename = _.last(filepath);
// option: need to check for templateRoot to strip?
if (options.templateRoot && filename.indexOf(options.templateRoot) === 0) {
filename = filename.replace(options.templateRoot, '');
filepath[(filepath.length - 1)] = filename;
grunt.log.writeln('Found templateRoot and stripped it from the template name: "' + filename + '"');
}
filepath = filepath.join('/');
filename = processFilename(filepath);
if (options.compress) {
src = src.split("\n");
for (var i = 0; i < src.length; i++) {
if (src[i].charAt(0) !== '<') {
src[i] = '{{!~}}' + src[i];
}
}
src = src.join("\n");
}
try {
compiled = require('handlebars').precompile(src, compilerOptions);
} catch (e) {
grunt.log.error(e);
grunt.fail.warn('Handlebars failed to compile '+filepath+'.');
}
// source is compiled at this point, let us reconstruct and decide wrappings
if (options.partials) {
wrapOpen = 'Handlebars.partials[\'' + filename + '\'] = template(';
} else {
wrapOpen = 'templates[\'' + filename + '\'] = template(';
}
// This optionally returns the template as well as adding it to the Handlebars.templates object for immediate use in AMD modules
if (options.returnAMD)
{
wrapClose = ');return templates[\''+filename+'\'];\n';
} else {
wrapClose = ');\n';
}
// finally, put it all back together
compiled = wrapOpen + compiled + wrapClose;
templates.push(compiled);
});
templates = templates.join(grunt.util.normalizelf(options.separator));
var wrappedTemplates = prefix + midfix + templates + suffix;
output = partials.concat(wrappedTemplates);
if (output.length < 1) {
grunt.log.warn('Destination not written because there was no output.');
} else {
if (options.min) {
output = uglify.minify(output, { fromString: true }).code;
}
grunt.file.write(f.dest, output);
grunt.log.writeln('File "' + f.dest + '" created.');
}
});
});
};