Improved template generation