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" "">
<html xmlns="">
<title>Hi there</title>
<h1>This is my template test: $, ${[1,2,3].length} ${[1].length}</h1>
<? function foo() { ?>
<table border="1">
<? for(var i = 0; i < 5; i++) { ?>
<? for(var j = 0; j < 5; j++) { ?>
<? for(var k = 0; k < 5; k++) { ?>
<? for(var l = 0; l < 5; l++) { ?>
<td>($i,$j,$k,$l,${{a: '1',b: '2',c: '3'\}.c})</td>
<? } ?>
<? } ?>
<? } ?>
<? } ?>
<? } ?>
<? foo(); foo(); foo(); ?>

Tuesday, February 13, 2007

Python's Files

I was reading the following comment:

What I didn't like about Python was the fact that OOP seems bolted on. For example, to open a file you use "f = open("text.txt")" but to close it you do "f.close()". Ruby is much more elegant in that everything is an object.

and I thought I'd explain Python files a little just in case someone else makes the same mistake. (And by the way, everything in Python is an object, too.)

In Python, the "open()" function is actually an alias for the "file()" constructor. Yes, that's right -- what the commenter thought pointed out a non-object-oriented aspect of Python actually illustrates Python's object-oriented nature. So you create a file object 'f' using 'f = file("text.txt")', and you close it you do "f.close()".