Refactor Code to support Generate Template