Refactor to use a single template loop