This stuff seems like a good candidate for a template tag.