Client templating with jQuery

by Lars-Erik Juntti 6. December 2008 12:33

Client templating is basically used for displaying JSON data on the page using a predefined HTML template. This technique is included in the preview of ASP.NET AJAX 4.0 but there is already a bunch of existing templating engines avaliable and we are going to take alook at a plugin for jQuery called jTemplates. jTemplates uses a basic syntax for displaying JSON data, creating for-loops and other logic in the template. This engine works wery well with the scriptproxy in ASP.NET AJAX and we are going to create a simple productlist to demonstrate this.

Lets start by creating the productservice, remember to attribute the serviceclass with the [ScriptService] tag to activate the AJAX proxy.

The servicemethod is pretty straightforward and returns a list of products, each including a title, description and image property.  The html in the aspx file doesn't contain that much, a container for the list to be rendered in and a loading text that will be replaced with the template content. 


It's time for the javascript part, and first of is defining the load method. This is put in the jQuery .ready() function which will execute when the DOM is fully loaded. 

  The LoadProducts makes an AJAX post to the GetProducts method in our sevice, if successfull we forward the returning JSON objects to our template engine. 



This will first set the template which is a standard .htm page including the jTemplate syntax and html. When it's set we execute the processTemplate method with the JSON objects passed in.



The template will return an unordered list with items, each with html for displaying the properties defined in our product object.



Finally the resulting list with some CSS added. jTemplates makes it wery easy to display your JSON data as html and at the same time gives us a clean separation of logic and presentation.

Tags: , ,

Development

blog comments powered by Disqus

Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.


Welcome to the Dropit blog!

Here we, the people that work at Dropit, will write about stuff that interests us. For example web development, especially with .NET and EPiServer - but we'll also talk about other techniques that interest us, marketing on the web, social phenomenons, pop culture, games and software development in general.