move template-related code to templates.go and some code to util.go