Using PURE a JavaScript template engine
Article Metadata
Code Example
Article
What is PURE?
Pure is a JavaScript template engine. It supports many JavaScript libraries and frameworks, like jQuery, prototype, DOMAssistant and MooTools.
It is meant for separating HTML representation from the JavaScript logic. This is a nice way to develop WRT widgets, especially if your data is in JSON format.
Read more form the Pure website.
How to use
In this article, we are using nice language identifying service called LangId to provide us some data in JSON format. After that, the returned data is rendered using Pure. We are using Pure in conjunction with the jQuery. jQuery provides us a simplified way to access elements and to do AJAX requests to LangId web API.
LangId web API is very simple and easy to use. For example the following query tries to determinate language in question when "i am baboon" is used as a reference sentence.
{{{1}}}
jQuery’s getJSON is used to fetch language data from LangId service.
$.getJSON("http://api.langid.net/identify.json?string="+sentence, function (data,textStatus){...});
Response is in JSON format as follows: "response":{"iso":"en","full-name":"English","img":"http:\/\/langid.net\/images\/flags\/48\/en.png"}}
As can be seen we will get ISO code, full name of the language and appropriate flag image from the LangID. The next step is to design a template that will be used to present that data to users:
Actual data is inserted into the template in the getJSON: s callback method. Directive tells to Pure how the data should be placed in to the template. Pure offers more advanced features as iteration and recursion, but we will settle for basic use case.
function (data,textStatus){
var directive ={"iso": data.response["iso"],
"img": data.response["img"],
"fullname":data.response["full-name"]};
$('#langinfo').autoRender(directive);
});
In the first line, we tell Pure to look for element that has class label “iso” and replace that value with the value obtained from the JSON formatted response. The same applies to "fullname" field. The image is a special case. As can be seen from the HTML code {{{1}}} the class attribute value is a bit different. With that syntax, we tell pure to insert value passed to it via img identifier to the src attribute of the image tag.
The last line initiates the rendering process. jQuery's are used to access div with {{{1}}} and autoRender() is called which performs the rendering. Please check out Pure Wiki for more examples and advanced use cases.
Additional material
Download the latest version of the Pure library and one of the supported javascript frameworks.
Download the example widget. Media:PureTemplates.zip



(no comments yet)