jquery pure templates
This story will be about jquery pure templates.
During developing new project I found great library Pure by beebole and I was going to write about it in first place. but with time when using it I found more and more issues with it. My first idea was to fix it, and I started doing that, but in the middle of debugging I found out it’s not that easy, 20KB of sources is hard to change.
So I have decided to write my own code, using very similar idea but different approach. My library is still pure, does not require putting fancy markers into html in manner to fill it with data, it is enough to write code which can be matched by jquery. My first try was with putting selectors directly into data description like:
data = {'a#my':"my url",'a#my@href':"#/url"}
After I got proof of concept in only 3 hours of coding I thought it would be good to allow mapping any keys to a map of selectors, so it is no more required to return selectors as keys of JSON:
data2 = {'name':"my url",'link':"#/url"}
using simple map file:
map2 = {'name':'a#my','link':'a#my@href'}
So how to call it ? Simple :) just include lib in the header:
<script src="jquery-pure-template.js" type="text/javascript" charset="utf-8"></script>
And call render on jquery matching elements:
$('.user').render(data);
or using map file:
$('.user').render(data2,map2);
Thats all needs this html:
<div class="user"><a href="#"></a></div>
and finally you will get as output this html:
<div class="user"><a href="#/url">my url</a></div>
This was simple example, but it will also work with arrays, and nested arrays too, just give it a chance, and keep in mind don’t force html to change the flow, try to make data keep the flow, not view.
Ofcourse there might be certain problems with performance with the chosen approach, first of all performance. Arrays over 500 elements tend to perform quite bad, but using nesting arrays can hold up to 5000 elements without big problem on decent computer. Additionally putting id’s into collection should additionally give some 20% speed up in finding elements by jquery.
I know there are faster solutions, that can probably render lots of data, but mine is simple, only 100 lines now (70 in first version), this makes it extremely easy to maintain and change, hawing less code is better then more :)
This post is also available in Polish version.
Software described here is a plugin for jquery.