Cleaned up the tempalte handler code and fixed unit tests