You could implement the code used in the admin templates to do it.