Simple & powerful client-side templating
DOWNLOAD
- ICanHaz.js – Uncompressed
- ICanHaz.min.js – Minified
- ICanHaz-no-mustache.js – Bring your own mustache (pick your own version just expects a
Mustache
global). - ICanHaz-no-mustache.min.js – Minified, no Mustache
Or… you can clone the whole project from GitHub with Git by running:
$ git clone git://github.com/andyet/ICanHaz.js
OKAY, LET’S DO THINGS
THE QUICK DEMO:
STEP 1. – DEFINE YOUR TEMPLATE
<script id="user" type="text/html">
<li>
<p class="name">Hello I'm {{ name }}</p>
<p><a href="http://twitter.com/{{ twitter }}">@{{ twitter }}</a></p>
</li>
</script>
STEP 2. – RETRIEVE YOUR POPULATED TEMPLATE:
// I Can Haz User?
var user = ich.user(user_data_object)
STEP 3. – THERE IS NO STEP 3!
WHAT ELSE DO I NEED TO KNOW?
For simplicity and ease of use, ICanHaz includes janl’s Mustache.js v0.4.0 (inside a closure) that way you can just include ICanHaz and then YOU CAN HAZ stuffs. Luckily Mustache and Mustache.js are generously MIT licensed. Mr. Github founder himself Chris Wanstrath (@defunkt) created mustache. Read the mustache documentation for more info. Then it was ported to JS by Jan Lehnardt.
WHY WOULD WE NEED THIS?
Because building html elements using javascript or jQuery is ugly. There’s several ways to do it, but the point is — it’s ugly.
// vanilla JS
hello_div = document.createElement('div');
hello_div.setAttribute('class', 'hello');
my_list = document.createElement('ul');
hello_div.appendChild(my_list);
list_item = document.createElement('li');
list_item.innerHTML = 'My list item';
my_list.appendChild(list_item);
// jQuery
hello_div = $('<div class="hello"><ul></ul></div>');
hello_div.children('ul').append('<li>My list<li>');
It gets really problematic if what you’re building is a lot longer or more complex than this example. Not to mention, it’s also not a clean separation of concerns to write html in javascript.
Mustache.js gives us an awesome templating solution, here’s a snippet from their docs:
var view = {
title: "Joe",
calc: function() {
return 2 + 4;
}
}
var template = "{{title}} spends {{calc}}";
var html = Mustache.to_html(template, view);
But the beauty fades when we’re dealing with multi-line html in the browser because strings in JS can’t include new-lines so everything has to be escaped. Then there’s the problem of double vs. single quotes and before you know it… we’re back in ugly land:
var template = '<div class="hello">\
<span class="title">{{ title }}</span>\
<ul></ul>\
</div>'
I CAN HAZ BETTER SOLUTION?
YES!
With ICanHaz.js you define your Mustache.js template snippets in script blocks of type="text/html" and give them an "id" as a title for your snippet (which validates, btw). This approach was suggested by jQuery developer @jeresig on his blog.Then, on document ready ICanHaz.js builds a cache of all the templates and creates a function for each snippet. All you have to do is say to yourself for example "I can haz user?":
var data = {
first_name: "Henrik",
last_name: "Joreteg"
}
// I can has user??
html = ich.user(data)
At this point ‘html’ is jQuery or Zepto (if they’re included) object containing your complete html with your data injected.
For each template you define (except partials), ICanHaz builds a retrieval function with the same name. If you don’t want a jQuery object but just want the populated string you can just pass in true
as the second argument to get the raw string. This is useful if your template isn’t producing html.
If you don’t have jQuery or Zepto, you can still use ICanHaz. You’ll just get strings back instead of jQuery objects.
I’M IN UR TEMPLATES, MAKING MACROZ.
ICanHaz.js also supports mustache partials. To quote the original mustache.js announcement:
Partials are good for including often-used snippets, like navigation or headers and footer.
In mustache, partials are dead simple. You have a special tag
{{>partial}}
that you put where you want to insert the partial, create the partial that you want to be displayed and that’s it. It is just a basic replace or macro include mechanism. Nothing fancy.
Just add your partial like any other template
<!-- Main template, includes the "winnings" partial. -->
<script id="welcome" type="text/html">
<p>Welcome, {{name}}! {{>winnings}}</p>
</script>
<!-- Partial included via {{>winnings}} -->
<script id="winnings" class="partial" type="text/html">
You just won ${{value}} (which is ${{taxed_value}} after tax)
</script>
Then call the main template normally.
ADDING TEMPLATES/PARTIALS LATER
Optionally, you can call ich.addTemplate(name, templateString)
or ich.addPartial(name, templateString)
to add templates and partials if you’d prefer to pull the from a server with ajax or whatnot. You can even do ich.grabTemplates
if you’ve loaded in some other page
AVAILABLE METHODS
Beyond the retrieval functions that ICanHaz creates based on template names, these additional methods exist.
ich.addTemplate(name, mustacheTemplateString)
: Add new template. Could be useful if you prefer not to use<script type="text/html">
approach or want to lazy load ’em from a server or whatnot.ich.clearAll()
: Clears templates and partials cache.ich.grabTemplates()
: Looks for any<script type="text/html">
tags to make templates out of. Then removes those elements from the dom (this is the method that runs ondocument ready
whenich
first inits).ich.refresh()
: Just clears all then grabs new templates. This could be useful for pages loaded with ajax that contain other templates.
EXAMPLES
FULL WORKING EXAMPLE
<!DOCTYPE html>
<html>
<head>
<title>ICanHaz.js Demo</title>
<script src="test/jquery-1.4.4.min.js"></script>
<script src="ICanHaz.min.js" ></script>
<script id="user" type="text/html">
<li>
<p>Hi I'm <a href="http://twitter.com/{{ twitter }}">@{{ twitter }}</a></p>
<p>I work for {{ employer }} as a {{ job_title }}.</p>
</li>
</script>
<script type="text/javascript">
// when the dom's ready
$(document).ready(function () {
// add a simple click handler for the "add user" button.
$('#add_user').click(function () {
var user_data, user;
// build a simple user object, in a real app this
// would probably come from a server somewhere.
// Otherwise hardcoding here is just silly.
user_data = {
name: "Henrik Joreteg",
twitter: "HenrikJoreteg",
employer: "&yet",
job_title: "JS nerd"
};
// Here's all the magic.
user = ich.user(user_data);
// append it to the list, tada!
//Now go do something more useful with this.
$('#user_list').append(user);
});
});
</script>
<style>
body {
font-family: Helvetica;
}
</style>
</head>
<body>
<h1>ICanHaz.js Demo</h1>
<h3>User List</h3>
<button id="add_user">Add User</button>
<ul id="user_list"></ul>
</body>
</html>
PULLING TEMPLATES FROM A REMOTE SERVER
$.getJSON('/myserver/templates.json', function (templates) {
$.each(templates, function (template) {
ich.addTemplate(template.name, template.template);
});
});