Valentino Volonghi's Weblog

Greetings mercenaries!

Thursday, December 01, 2005

Random image rotators everywhere

After I came across this I decided that I should write something about the same thing but done in Nevow.
First of all the task is to write a random image rotation implementation for jpegs, gifs and pngs. This is easily accomplished by doing the following 3 things:

1. Add this to the root Page of your web site. 'random/images/directory' is a directory in your HDD containing lots of images and other random data.
child_random_images = static.File('random/images/directory')

2. Add this to each of your Page objects that use the random image (or use a common base class to have this behaviour everywhere for free):
def render_random_image(self, ctx, data):
files = [f for f in os.listdir('random/images/directory')
if os.path.splitext(f)[1] in ['.jpg', '.gif', '.png']]
return ctx.tag(src='/random_images/'+random.choice(files))

3. Use the following tag wherever you want to have a randomly rotated image in your web app:
 <img nevow:render="random_image" alt="Random Image" /> 

Now you have a wonderfully randomly rotated image in your web browser and with 2 lines less than the Ruby On Rails counterpart without sacrifying readability too much.


At 12:13 PM, Anonymous Micetto Nero said...

Primo! :-)

At 9:45 PM, Anonymous Anonymous said...

Have you seen this women directory?


Post a Comment

Links to this post:

Create a Link

<< Home