Tiny Client-Side jQuery Templating Plugin

I made this plugin up to help debug some things, it might come in handy one day.

Code Follows!

jQuery.fn.extend({
        template: function(context, user_opts) {
            var opts = {
                save : false
            };
            $.extend(opts,user_opts);
            $.each(this, function() {
                    var template_container = $(this).find('span.template');
                    if (template_container.length <= 0) {
                        template = $(this).html();
                        $(this).html('');
                        $(this).append('<span class="template">'+template+'</span>');
                        template_container = $(this).find('span.template');
                    } else {
                        template = template_container.html();
                    }
                    for (var key in context) {
                        template = template.replace(new RegExp('{{'+key+'}}','g'), context[key]);
                    }

                    var target = $(this).find('span.render');
                    if (target.length <= 0) {
                        $(this).append('<span class="render"></span>');                
                        target = $(this).find('span.render');
                    }
                    target.html(template);
                    if (opts.save == true)  {
                        template_container.html(template);
                    }
                });
        }
    }
    );

Leave a Reply

Your email address will not be published. Required fields are marked *