jQuery Plugin: template

December 3, 2009 | Download

jQuery template is a port of Prototype's templating system. For the most part the two function the same, but with a small performance boost in this port by not calling a function on every match. Prototype's great documentation or examples are the place to start, but here's a summary.

Usage

jQuery.template stores strings with embedded symbols in the form of #{name}. The function returns an object containing the template, pattern, and an eval function to convert with. The eval function takes a single object parameter that contains the key=>value pairs to transform the template with.

Example
jQuery(function($){
	var MyTemplate = $.template("<li>#{value}</li>");

	var converts = [
		{value: 'This'},
		{value: 'Gets'},
		{value: 'Evaluated'}
	];

	for (var i in converts){
		$('ul#template-eval').append(
			MyTemplate.eval( converts[i] );
		);
	}
});

    Customize

    Escaping symbols and Custom syntax is supported under the condition that the same format is used. The first match must be of the character before the symbol to catch escaped symbols, the second match must contain the entire symbol for replacement, and the third match must contain the key to check against the object to replace with. Below are some suggested pattern formats.

    // Original format
    /(^|.|\r|\n)(#\{(.*?)\})/
    
    // '$' instead of '#'
    /(^|.|\r|\n)($\{(.*?)\})/
    
    // <%= name %> like conversions
    /(^|.|\r|\n)(\<%=\s*(\w+)\s*%\>)/
    
    // PHP Type (<?= ?>) syntax
    /(^|.|\r|\n)(\<\?=\s*(\w+)\s*\?\>)/
    

    You really have to thank the Prototype guys for this simple templating system. Below is the source code and download package which includes a test page with a few examples of it's usage.

    /*!
     * jQuery Template
     * November 5, 2009
     * Corey Hart @ http://www.codenothing.com
     *
     * A port of Prototype's templating system @ http://www.prototypejs.org/api/template
     */
    ;(function($, undefined){
    var
    	// Variable Pattern Match
    	Pattern = /(^|.|\r|\n)(#\{(.*?)\})/,
    
    	// Template function, returns an object that contains
    	// the template and the pattern
    	Template = function(template, pattern){
    		// Join array based template passed
    		this.template = $.isArray(template) ? template.join('') : template||'';
    
    		// Set user defined pattern, or just use base pattern
    		this.pattern = pattern||Pattern;
    
    		// Add evaluation function that keeps original template intact, 
    		// while returning converted temp
    		this.eval = function(obj){
    			var temp = this.template, lastIndex = 0, match, m;
    
    			// Ensure object format
    			if (obj === undefined || typeof obj !== 'object')
    				obj = {};
    
    			// All patterns matched need to be replaced with their respective values, or
    			// with an empty string. When looping, be sure to only execute the pattern
    			// on the part of the string that has yet to be transformed
    			while (match = this.pattern.exec(temp.substr(lastIndex))){
    				// Pass over escaped formats and remove their lingering '\'
    				if (match[1] === "\\"){
    					lastIndex = temp.indexOf(match[0]) + match[0].length;
    					temp = temp.replace(match[0], match[0].substr(1));
    				}else{
    					m = match[3];
    					lastIndex = temp.indexOf(match[0]) + (obj[m] ? obj[m].length : 0);
    					temp = temp.replace(match[2], obj[m] ? obj[m] : '');
    				}
    			}
    
    			return temp;
    		}
    	};
    
    	// Attach template to jQuery
    	$.template = function(template, pattern){
    		return new Template(template, pattern);
    	};
    })(jQuery);
    

    Download

    Latest: template.zip
    Released: December 3, 2009
    -Initial Release
    Have a question or comment? ask@codenothing.com.