Refactor and fix service template logic