Thursday, October 7, 2010

Create html with data using JQuery templete

I wish it. JQuery is great.
({data model} is json syntax) + (<script>html template</script>) => html page and more



<html>
<body>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery.tmpl.js" type="text/javascript"></script>

<div id="pager">sain baina uu?</div>

<script>

(function($) {

    $.fn.msgbox = function(options) {

        var opts = $.extend({}, $.fn.msgbox.defaults, options);
        //alert(this.get(0));
        return this.each(function() {           
            alert($(this).text());
        });
    };
   
    $.fn.msgbox.defaults = {
        pagenumber: 1,
        pagecount: 1
    };
   
})(jQuery);

//$("#pager").msgbox({options: "fix"});

</script>

<script id="tmplPeople" type="text/x-jquery-tmpl">
<tr class="${alternate($data, people)}"><td colspan="2"><a href="${url}">${getName()}</a></td></tr>
{{each cities}}
<tr class="cityseparator"><td colspan="2"></td></tr>
<tr class="${alternate($data, people)}"><td colspan="2"><b><i>City ${index($value, cities)}:</i></b></td></tr>
<tr class="${alternate($data, people)}"><td><b>${name}</b></td><td>${state}</td></tr>
{{/each}}
<tr class="separator"><td colspan="2">{{if cities}} {{/if}}</td></tr>
</script>

<script type="text/javascript">

var dataObject = {
    firstName: "John",
    lastName: "Resig",
    url: "http://ejohn.org/",
    cities: ["Boston, MA", "San Francisco, CA"]
};

var people = [
{firstName: "John", lastName: "Resig", url: "http://ejohn.org/",
    cities: [
        { name: "Boston", state: "MA" },
        { name: "San Francisco", state: "CA" }
    ]},
{firstName: "Dave",lastName: "Reed",url: "http://dave.org/",
    cities: [
        { name: "Seattle", state: "WA" },
        { name: "Los Angeles", state: "CA" },
        { name: "New York", state: "NY" }
    ]},
{firstName: "Boris",lastName: "Moore",url: "http://boris.org/",
    cities: [
        { name: "Redmond", state: "WA" }
    ]}
];

function cityJoin( separator ) {
    return this.data.cities.join( separator || ", " );
}

function getName() {
    return this.data.firstName + " " + this.data.lastName;
}

function index( item, array ) {
    return $.inArray( item, array ) + 1;
}

function alternate( item, array ) {
    return ($.inArray( item, array ) % 2) ? "personAlt" : "person";
}

jQuery(function(){
    // A template string
    var tmpl = '<li><a href="${url}">${cityJoin()}</a>';
    tmpl += ' {{if $item.showCities}} (${cityJoin()}) {{/if}} </li>';

    $.tmpl( tmpl, dataObject ).appendTo( "ul" );
});


$(function(){
    $("#tmplPeople").tmpl( people ).appendTo(".peopleTable");
});


</script>

<ul></ul>

<table class="peopleTable"><tbody>
<tr class="separator"><td colspan="2"></td></tr>
</tbody></table>

</body>
</html>

No comments: