forked from HenrikJoreteg/ICanHaz.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ICanHaz.js
87 lines (71 loc) · 2.97 KB
/
ICanHaz.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
/*!
ICanHaz.js version 0.6 -- by @HenrikJoreteg
Licensed under the "You should follow @HenrikJoreteg on Twitter to use this" license. (Because, apparently I'm a twitter whore like that)
This is a simple template storage and retrieval system.
Templates are stored in the document as script elements with type="text/html". Cheers to @jeresig for this idea.
They are processed through Moustache.js for templating.
Dependencies:
- Mustache.js
- jQuery
Documentation at: http://github.com/HenrikJoreteg/ICanHaz.js
*/
// JSLint Config
/*global jQuery Mustache */
var ich;
(function ($) {
function ICanHaz() {
var that = this,
spec = {
cache: {},
partials: {}
};
this.VERSION = "0.6";
// public function for adding templates
this.addTemplate = function (name, templateString) {
// We're enforcing uniqueness to avoid accidental template overwrites.
// If you want a different template, it should have a different name.
if (spec.cache.hasOwnProperty(name)) {
throw "ICanHaz error? Yes. You've already got a template by the name: \"" + name + "\"";
} else {
// cache it
spec.cache[name] = templateString;
// build the corresponding public retrieval function
that[name] = function (data, raw) {
data = data || {};
var result = Mustache.to_html(spec.cache[name], data, spec.partials);
return raw ? result : $(result);
};
}
};
// public function for adding partials
this.addPartial = function (name, templateString) {
if (spec.partials.hasOwnProperty(name)) {
// check for partial
throw "ICanHaz error? Yes. You've already got a partial by the name: \" + name + \"";
} else {
spec.partials[name] = templateString;
}
};
// Loop through and add templates.
// Whitespace at beginning and end of all templates inside <script> tags will
// be trimmed. If you want whitespace around a partial, add it in the parent,
// not the partial. Or do it explicitly using <br/> or
$('script[type="text/html"]').each(function () {
var script = $(this),
name = script.attr('id'),
text = $.trim(script.html()),
isPartial = script.attr('class').toLowerCase() === 'partial';
if (isPartial) {
that.addPartial(name, text);
} else {
that.addTemplate(name, text);
}
// remove the element from the DOM
script.remove();
});
}
// init itself on document ready
$(function () {
ich = new ICanHaz();
});
})(jQuery);