-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
224 lines (183 loc) · 6.12 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
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// var _ = {
// each: require('lodash.each'),
// defaults: require('lodash.defaults'),
// extend: require('lodash.extend'),
// clone: require('lodash.clone'),
// range: require('lodash.range')
// },
var _ = require('lodash');
var Minimize = require('minimize')
var minimize = new Minimize();
var handlebars = require('handlebars'); // parens will prevent browserify from packaging.
var defaultViewResolver = (typeof(window) === 'undefined') ? require('./viewresolver') : null;
var bwHandlebars = function() { };
/**
* Attaches and initializes the plugin.
* @params options.helpers {Object} key/value dictionary of handlerbar helpers. key is the name and val is the function.
* @params options.optimize {Boolean} Compresses and removes whitespace from markup.
* @params options.development {Boolean} If true, then templates are fetched and compiled every time they are rendered.
* @params options.viewResolver {Object} if absent, then a file system view resolver is used to get the markup from the file system.
**/
bwHandlebars.prototype.attach = function (options) {
// support the factory if exists - https://github.com/tommydudebreaux/handlebars.js
// otherwise, use the default singleton approach here.
var Handlebars = handlebars.create ? handlebars.create() : handlebars;
_.defaults(options, {
helpers: {},
optimize: false,
development: true,
view: {
base: (typeof(window) === 'undefined') ? process.cwd() : null,
ext: "html"
}
});
var viewResolver = options.viewResolver || new defaultViewResolver(options.view),
templateCache = {};
// Override the default version of each.
Handlebars.registerHelper('each', function(context, options) {
var buffer = [],
that = this;
_.each(context, function(v, k) {
try {
buffer.push(options.fn(_.extend(_.clone(that), { key: k, value: v })));
}
catch (e) {
buffer.push(e);
}
});
return buffer.join('');
});
// Create a range function that will iterate numbers from 0 -> max
// This is mirrors the underscore _.range function.
// http://documentcloud.github.com/underscore/#range
Handlebars.registerHelper('range', function(expression, options) {
var buffer = [],
stop = 0,
that = this;
if (typeof(expression) == 'string') {
with(this) {
stop = eval(expression);
}
}
else {
stop = expression;
}
_.each(_.range((options.hash.start || 0), stop, (options.hash.step || 1)), function(v, k) {
try {
buffer.push(options.fn( _.extend(_.clone(that), { key: k, value: v })));
}
catch (e) {
buffer.push(e);
}
});
return buffer.join('');
});
// if with evaluation.
Handlebars.registerHelper('ifeval', function(expression, options) {
var conditional = false;
with(this) {
conditional = eval(expression);
}
return conditional ? options.fn(this) : options.inverse(this);
});
// Similar to standard print {{value}}, but with an optional fallback value.
// Ex: {{def foo def="goo"}} will print the value of foo if exists, otherwise it will print "goo"
// If def is omitted, then an empty string is printed.
Handlebars.registerHelper('def', function(expression, options) {
var val = null,
def = options.hash.def || '';
try {
with(this) {
val = eval(expression);
}
}
catch (e) {
val = expression;
}
return val ? val : def;
});
// Allowing dynamic loading of partials based on value of variable in context
// Call is made like {{{partial "partial.root" partial_name ctx}}} or {{{partial full_partial_string ctx}}}
Handlebars.registerHelper('partial', function(root, name, ctx, hash) {
var ps = Handlebars.partials, path;
if (typeof name === 'object') {
var tmp = name;
name = '';
hash = ctx;
ctx = tmp;
} else if (typeof name === 'undefined') {
name = '';
};
path = root + ((name !== '') ? ('.' + name) : name);
if(typeof ps[path] != 'function')
ps[path] = Handlebars.compile(ps[path]);
return ps[path](ctx, hash);
});
// Inject external handlebar helpers.
_.each(options.helpers, function(fn, name) {
Handlebars.registerHelper(name, fn);
});
/**
* Attaches to a Broadway app and exposes the render function
* @params view {String} The name of the view to render. This will be used by the view resolver to pull markup from file system (node.js) or other (client js)
* @params data {Object} The view model to use when rendering.
* @params callback {Function} Notifies when render is complete. callback(err, data)
**/
this.render = function (view, data, callback) {
var template = templateCache[view];
// are we in debug or was it already compiled
if (!options.development && template) {
_render(view, data, callback);
}
else {
// otherwise get and compile.
viewResolver.all(function(err, dict) {
if (err) {
callback(err);
}
else {
// register each partial in case it is needed by view.
_.each(dict, function(markup, key) {
Handlebars.registerPartial(key.replace(/\//g, '.'), markup);
});
// Compile and render the top level view.
_compile(view, dict[view]);
_render(view, data, callback);
}
});
}
};
// expose the instance of hb so that helpers or other things can be attached async.
this.render.instance = Handlebars;
var _compile = function(view, markup) {
// remove whitespace if html compression is on.
if (markup && options.optimize) {
markup = markup.replace(/\s+/gi, ' ');
}
templateCache[view] = markup ? Handlebars.compile(markup) : function() { throw new Error("View Not Found - " + view); };
return templateCache[view];
};
var _render = function(view, data, callback) {
var template = templateCache[view],
html = null,
err = null;
// render
try {
html = template(data);
}
catch (e) {
err = e;
}
if (options.minify) {
minimize.parse(html, function (error, data) {
return typeof(callback) === 'function' ? callback(error, data) : null;
});
} else {
return typeof(callback) === 'function' ? callback(err, html) : null;
}
};
this.templates = function(callback) {
viewResolver.all(callback);
};
};
module.exports = bwHandlebars;