Fix template cache memory leak