-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathjquery.render.js
executable file
·56 lines (48 loc) · 1.47 KB
/
jquery.render.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
/*!
* js-jquery-render
* -------------
* Simple template method for jQuery
*
* @version 1.1.0
* @license MIT
* @author mach3 <http://github.com/mach3>
* @require jquery#1
*/
(function($, undefined){
$.fn.extend({
/**
* Function to render HTML from template and data
*
* @param {Object} data - Collection of data ( array or object )
* @param {Boolean} render - Return jQuery object or not
* @return {jQueryObject|String}
*
* @example:
* $("script#template-example")
* .render(data)
* .appendTo("#container");
*/
render: function(data, render){
var tmpl, html, create;
tmpl = this.html();
html = "";
create = function(t, d){
var m = t.match(/\{\{(.+?)\}\}/g) || [], r = t;
$.each(m, function(i, k){
var v = d[ k.replace(/\{|\}/g, "") ];
r = r.replace(k, ( v === undefined ) ? "" : v);
});
return r;
};
data = (data === undefined) ? {} : data;
render = (render === undefined) ? true : false;
if(! (data instanceof Array)){
data = [data];
}
$.each(data, function(i, o){
html += create(tmpl, o);
});
return render ? $("<div>").html(html).children() : html;
}
});
}(jQuery));