using Javascript functions within the Jade templating language

Recently I've enjoyed using the Jade templating language for making HTML templates -- I really like the syntax, which, like Python, uses white space and indentation to organize content in an HTML document:

!!! 5
    title my new document
      if (foo) {

    h1 welcome
      p this is the text

One useful feature is the ability to run arbitrary javascript functions directly in the templates. You can think of this as a "filter" that can be used to transform data. To add a function to a .jade template, just use the following code syntax, in this case a function that transforms integers into hex:

- var intToHex = function(i){  
-   i=parseInt(i);if(i < 0){i = 0xFFFFFFFF + i + 1;}
-   return lPad(i.toString(16));
- }

- var lPad = function(s){ while(s.length<6){s="0"+s;}return s;}

Then you can use this function to transform data as you need:

  p #{intToHex(my_int)}

As far as I know you can use any standard javascript in these functions, making them useful for simple data and formatting transformations. If you are using template inheritance, make sure to keep these function definitions inside of a block to keep them within scope.