Created
October 4, 2018 06:43
-
-
Save kaizer1v/a18b611f2c9c804b965c536527133192 to your computer and use it in GitHub Desktop.
jQuery template plugin using lodash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<title>jQuery Templating</title> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> | |
</head> | |
<body> | |
<h1 class="h"> | |
<script type="text/html">Some text added. <%= txt %></script> | |
</h1> | |
<ul> | |
<script type="text/html"> | |
<% for(var i = 0; i < nums.length; i++) { %> | |
<li><%= nums[i] %></li> | |
<% } %> | |
</script> | |
</ul> | |
<table> | |
<thead> | |
<tr> | |
<th>one</th> | |
<th>two</th> | |
<th>three</th> | |
</tr> | |
</thead> | |
<tbody> | |
<script type="text/html"> | |
<% for(var i = 0; i < rows.length; i++) { %> | |
<tr> | |
<td><%= rows[i]['one'] %></td> | |
<td><%= rows[i]['two'] %></td> | |
<td><%= rows[i]['three'] %></td> | |
</tr> | |
<% } %> | |
</script> | |
</tbody> | |
</table> | |
<script type="text/javascript" src="node_modules/lodash/lodash.min.js"></script> | |
<script type="text/javascript" src="node_modules/jquery/dist/jquery.min.js"></script> | |
<script type="text/javascript"> | |
// a quick jquery plugin | |
$.fn.template = function(data) { | |
var elem = this | |
// need to figure out how to generalize this | |
var script = elem.find('script[type="text/html"]') | |
var c = _.template(script.text()) | |
elem.html(c(data)) | |
} | |
// usage | |
$('h1').template({ txt: 'some random text' }) | |
$('ul').template({ nums: 'some random text'.split(' ') }) | |
$('table tbody').template({ rows: [ | |
{ | |
one: 'one', | |
two: 2, | |
three: false | |
}, { | |
one: 'one one', | |
two: 22, | |
three: true || false | |
}, { | |
one: 'one noe eon', | |
two: 232, | |
three: 'undefined' | |
} | |
]}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment