factored out common template generation code