refactored into writeTemplate