Refactor to make the template rendering logic its own function