improved template handling