Web Dynamism w/Python+jQuery - Part 2  April 22nd, 2008

This is part 2 of a 3 part series. Check out part 1 and part 3.

Here's a really easy one. The blurb and talk of requirements at the top of part 1 also apply to this article.

The Example

Let's say you have time-sensitive pages of some sort. Deadlines in the accounting field or something like a news page. You often will note somewhere on the page when the last time you edited it was. Can you count how many times you've forgotten to update it? It's easy to overlook and it makes you look bad. It's especially easy to forget if there's more than one page you need a timestamp on.

Let's fix that with a really quick Python script and some jQuery.

This one wont work without JavaScript enabled in the client's browser. Fortunately the timestamp will simply be missing so that's not a huge loss.

The Container

So first we'll need to decide where on the page to put our timestamp when it comes in. I'm just going to go with a simple div#footer element.

As long as we've got a way to traverse the DOM to this element we're OK. So you could really put it anywhere you like.

The Python CGI

This is pretty simple too.

So we've got a TIMEZONE constant set to -5 (because I'm in EST), then we're getting the current working directory and joining it with the file path we'll send from the page, grabbing a timestamp and sending it back to the page.

The JavaScript

Even though this is a super simple example, it's still a good opportunity for some organization. Make a new file somewhere in your site's hierarchy (like /js/common.js) with the following function:

Now we can use this in any page simply by changing our javascript includes accordingly. We just add our newly created 'library' right after the jQuery include:

When you view the page at this point you'll see nothing interesting going on. This is what it will look like to a non-JavaScript enabled browser, so make sure your CSS/etc doesn't break here. Once we're sure our layout wont explode on incapable browsers we can actually call our function:

That's all there is to it! Of course, you could easily expand on this idea. Instead of showing just the timestamp for the current page, you could have a list of pages, getting their links and showing the last modified time for each. Say you had an unordered list with id="links":

The Demo

The demo isn't very exciting this time :), but does include the 'enhancement' above. The demo is now offline.

The Rest

Sometimes it's the little things that save you time here and there which are really worth something. If I had 15 pages that all needed timestamps I think something like this could turn out to be very handy not only in making sure I don't forget to update it, but also just to save myself the work entirely.

Some social stuff: