Refactoring template middleware