Refactor template handling