What is BabaJS
BabaJS is an open source Javascript template engine/manager.
The basic concept is: Template + Data = HTML
Here is a simple example:
<!-- user template -->
<div class="user">
<span>< %=data.userName%></span>
< %IF data.hasPic %>
<img src="<% return 'http://imgs.mydomain.com/'+ data.userPic; %/>" />
< %ELSE%>
<span>Add User Pic</span>
< %ENDIF%>
<span>User Friends:</span>
< % var myUserName = data.userName; %>
< %LOOP for( var i=0; i< data.friends.length; i++ ) %>
<div class="friend">User < %=i%></div>
< % return this.includeTemplate("friend", window.getFriend( data.friends[i] ) ); %>
< %ENDLOOP%>
</div>
<!-- friend template -->
<div class="friend">< %=myUserName%> is friend with < %=data.userName%></div>
Javascript code to generate the HTML:
BabaJS.generateHTML({
templateName:"user",
requires:["friend"],
ready: function(html){
document.getElementById("test").innerHTML = html;
},
{userName:"me",
hasPic: true,
userPic: "me.jpg",
friends:["amir","baba","daniel","mia","yael"]}
);
The template manager will fetch the template and its dependency templates and will call the ready callback when the HTML is ready.
or you can just do something even simpler like so:
var html = BabaJS.generateHTML("<div>< %=data.userName%></div>",{userName:"me"});
document.getElementById("test").innerHTML = html;
It is as simple as that. but you can do so much more with BabaJS – so in this case RTFM is worth it.
Why I Developed it?
While developing a social network at Crytek i did a research at the current javascript templating engines out there. While there were some good solutions, like PURE and EJS, non of them were good fit for my requirements, so i started developing something very simple by my own. I decided to make it an open source project since I wanted to share it with the developing community and thought that maybe there are others that may benefit from it and aren’t happy with the existing solutions.
Main Features
- Sub Templating – you can include additional templates from other template as much as you like.
- Dependency Management – BabaJS keep track about dependencies between templates and JS and CSS files to make sure all are loaded when needed.
- Fast – BabaJS compiles the templates in order to achive fast execution.
- Template Stack Variables – BabaJS allows you to define variables in the template tags and access them from anywhere in the template or from included templates.
- Text Based - BabaJS is doing text manipulation and doesn’t work on the DOM elements, thus allowing it to work on Node.JS as well.
- Template Manager – BabaJS is not only a template engine, but also a manager that provides API to add/remove and create dependencies between templates.
