ICanHaz.js Templating Issues

Posted by & filed under , , .

iStock_000016987294XSmall servers bitsI’ve only just discovered ICanHaz.js I have to admit and as such I’m a bit of a moron when it comes to using it I guess. Still though, I felt the need to write up on this as I’ve been digging around the net for a while and the only resource helpful that I found on it was this: http://blog.mitchcrowe.com/blog/2011/09/14/javascript-templates-to-the-rescue/ . However, I feel that post is a bit misleading — whether it was based on a previous version of the library or I’m doing something wrong! Hence the post, for which I am eagerly waiting comments!

In case you didn’t know, ICanHaz.js is a library for easy templating on the client side — it allows for you to define a script block which contains your template, place a few markers inside it then render it via a simple call to the library where you pass in the object which contains the data to be filled in. Here’s a short example — which by the way uses both JQuery and ICanHaz.js (which is allowed by the way):

<script id="person" type="text/html">
<li>
<input type="text" value="{{name}}" />
<input type="text" value="{{age}}" />
</li>
</script>
 
<script type="text/javascript">
var me = { "name": "Liviu", "age":"guess!"};
$("#container").append(ich.person(me));
</script>

As you can see it’s pretty easy using it: you declare your template in a <script> tag (pay attention to type="text/html" — not text/javascript!) then simply append it to the DOM and pass in an object containing the data. Awesome!

This works great if you only want to fill in simple textual data — so if you’re only looking to generate <div>‘s or similar with text inside it this is fine; similarly, if you’re generating forms with just text and textarea objects inside it this approach is perfect.

What happens though when you are trying to add in things like checkboxes?

As the above link suggests, we use a conditional {{#marker}} ... {{/marker}} — something like this:

<script id="person" type="text/html">
<li>
<input type="text" value="{{name}}" />
Registered? <input type="checkbox" {{#registered}}checked="checked"{{/registered}} />
</li>
</script>
 
<script type="text/javascript">
var me = { "name": "Liviu", "registered":"true"};
$("#container").append(ich.person(me));
</script>

This suggests that the checked="checked" bit only gets added if the object/data’s registered property evaluates to true. The reality is though it doesn’t do that — instead what it does is this:

If the object/data has a property registered then it displays the checked="checked". It doesn’t matter about the value of that property — so even if the property value is false it will still display it — which is of course not what’s desired.

Took me a few hours of figuring this one out 🙁

P.S. Not sure what the answer to using ICanHaz.js with checkboxes is still btw! 🙁

Leave a Reply

Your email address will not be published.