refactored template handling