forked from hanachin/karma-handlebars-preprocessor
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
56 lines (43 loc) · 1.82 KB
/
index.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
var handlebars = require('handlebars');
/**
* config options:
* - transformPath - function that transforms original file path to path of the processed file
* - templateName - function that translates original file path to template name
* - templates - name of the variable to store the templates hash
*/
var createHandlebarsPreprocessor = function(args, config, logger) {
config = config || {};
var log = logger.create('preprocessor.handlebars');
var transformPath = args.transformPath || config.transformPath || function(filepath) {
return filepath.replace(/\.hbs$/, '.js');
};
var templateName = args.templateName || config.templateName || function(filepath) {
return filepath.replace(/^.*\/([^\/]+)\.hbs$/, '$1');
};
var templates = args.templates || config.templates || "Handlebars.templates";
return function(content, file, done) {
var processed = null;
log.debug('Processing "%s".', file.originalPath);
file.path = transformPath(file.originalPath);
var template = templateName(file.originalPath);
if(config.amd) {
processed = "define(['handlebars'], function(Handlebars) {\n" +
" return Handlebars.template(" + handlebars.precompile(content) + ");\n" +
"});";
} else {
try {
processed = "(function() {" + templates + " = " + templates + " || {};" +
templates + "['" + template + "'] = Handlebars.template(" +
handlebars.precompile(content) + ");})();";
} catch (e) {
log.error('%s\n at %s', e.message, file.originalPath);
}
}
done(processed);
};
};
createHandlebarsPreprocessor.$inject = ['args', 'config.handlebarsPreprocessor', 'logger', 'config.basePath'];
// PUBLISH DI MODULE
module.exports = {
'preprocessor:handlebars': ['factory', createHandlebarsPreprocessor]
};