This is probably too much code to have in a view. Can you put it in a helper method instead?