JavaScript Templating

Hi all as said in my previous post here i am to explain you how to write the java script templating and render UI with content dynamically.
sincere thanks to John Resig for his micro templating.
well the template engine is simple and it converts the dynamic scripts into pure javascript at runtime and the code is as follows. Please add the below script to a file and name it as “templating.js”

/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function() {

    var cache = {};

    this.tmpl = function tmpl(str, data) {
        // Figure out if we're getting a template, or if we need to
        // load the template - and be sure to cache the result.
        var fn = !/\W/.test(str) ? cache[str] = cache[str]
                || tmpl(document.getElementById(str).innerHTML) :
                // Generate a reusable function that will serve as a template
                // generator (and which will be cached).
                new Function("obj",
                "var p=[],print=function(){p.push.apply(p,arguments);};"
                +
                // Introduce the data as local variables using with(){}
                "with(obj){p.push('"
                +
                // Convert the template into pure JavaScript
                str.replace(/[\r\t\n]/g, " ").split("<%").join("\t")
                .replace(/((^|%>)[^\t]*)'/g, "$1\r").replace(
                /\t=(.*?)%>/g, "',$1,'").split("\t")
                .join("');").split("%>").join("p.push('")
                .split("\r").join("\\'")
                + "');}return p.join('');");

        // Provide some basic currying to the user
        return data ? fn(data) : fn;
    };
})();

After this my index page looks like this:

<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" charset="utf-8" src="js/jquery-1.7.2.min.js"></script>
        <script type="text/javascript" charset="utf-8"
        src="js/templating.js"></script>
        
    </head>
    <body>
        <div id="TempalateHolder"></div>
	<div id="PageHolder"></div>
    </body>
</html>

In the “TemplateHolder” div all the templates gets loaded and dymanically the content gets loaded in “PageHolder” div.
and my templates look like this, and name the file as templates.html

<script type="text/html" id="displayDates_tmpl">
    
    <% for(i=0;i<10;i++){ %>
        <h4>Sample <%=i%> .</h4>
    <% } %>
</script>

now inorder to render this template in the page please add the below script to the templating.js file as follows.

var ObjectManager = {
    Version: '1.0',
    init: function() {
        $(document).ready(function() {
            try { // fix IE background image flicker (credit:
                // www.mister-pixel.com)

                $(document).ready(function() {
                    // Load Templates here to store all template in
                    // TempalateHolder Div
                    $("#TempalateHolder").load("Templates.html", function() {
                        ObjectManager.ShowDatesPage();

                    });

                });

            } catch (err) {
                console.log(err);
            }
        });
    },
    ShowDatesPage: function() {
        this.ShowPage("displayDates", "");
    },
    ShowPage: function(PageName, DataObject) {
        var TemplateContent = tmpl(PageName + "_tmpl", DataObject);
        $("#PageHolder").html(TemplateContent);
    }
};

ObjectManager.init();

Happy Coding 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s