[Template] factored out the template building code, almost ready to integerate