Pages

Friday, February 23, 2007

Templates in Javascript

For my own use, and now also my employer's, I have created a simplistic Javascript templating library "JST". Basically, it compiles a simple templating language into an executable Javascript function which generates HTML. It's mainly useful for replacing DOM generation in Javascript (which is slow) with a fast function which builds a string that you can use to set the .innerHTML property of certain DOM nodes (which is fast).

If you're interested, I'm at PyCon in Dallas this weekend and would be glad to show off the code if you're here, too. (I may end up doing a 5-minute lightning talk about it). If this interests you, or if you want a copy of the JST => Javascript compiler, send me an email or leave a comment. Just to whet your appetite, here's a sample template that makes three really big nested tables (outer tables are 5x5, each cell of which is another 5x5 table). Using JST, these tables can be rendered by Firefox in less than 2 seconds.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hi there</title>
</head>
<body>
<h1>This is my template test: $v.name, ${[1,2,3].length} ${[1].length}</h1>
<? function foo() { ?>
<table border="1">
<? for(var i = 0; i < 5; i++) { ?>
<tr>
<? for(var j = 0; j < 5; j++) { ?>
<td>
<table>
<? for(var k = 0; k < 5; k++) { ?>
<tr>
<? for(var l = 0; l < 5; l++) { ?>
<td>($i,$j,$k,$l,${{a: '1',b: '2',c: '3'\}.c})</td>
<? } ?>
</tr>
<? } ?>
</table>
</td>
<? } ?>
</tr>
<? } ?>
</table>
<? } ?>
<? foo(); foo(); foo(); ?>
</body>
</html>

1 comment:

  1. Hi Rick. I stumbled across this post, and it got me all excited because a friend of mine (Essien) and I were talking about this a while back.
    I'd love to see your code, and possibly use it. I can't seem to find your e--mail address anywhere though, so here's mine: stan _dot_ madueke _at_ gmail _dot_com_. Holler back.

    ReplyDelete