Skip to content

Instantly share code, notes, and snippets.

@atkinson
Created December 17, 2013 03:07
Show Gist options
  • Save atkinson/7999356 to your computer and use it in GitHub Desktop.
Save atkinson/7999356 to your computer and use it in GitHub Desktop.
Easy jQuery templating
/*
Author: Rich Atkinson [email protected]
*/
// Provides a String.render() method. Similar to String.format() (in c),
// except it takes a literal object of name / value pairs, like context in Django.
// eg: "Hello {name} welcome to {list}".format({name: 'Joe', list: 'Spam'})
if (!String.prototype.render) {
String.prototype.render = function(dict) {
return this.replace(/{\s?([A-Za-z0-9\-_]+)\s?}/g, function(match, key) {
return typeof dict[key] != 'undefined' ? dict[key] : match;
});
};
}
// And a jQuery plugin so that you can String.render to render templates in JS much like you do in Django.
//
// for example:
//<script type="text/html" id="info-popup">
// <div class="info-popup">
// { message } { name }
// </div>
//</script>
//
// usage:
//
// $('.target-element').render_template('#info-popup', {message: 'Hello', name: 'world'});
//
(function( $ ) {
$.fn.render_template = function(template, context) {
if (! template) throw "'template' must not be null";
var rendered = $( template ).html().render( context );
return this.each(function() {
$( this ).html( rendered );
});
};
}( jQuery ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment