ah, this is to get the cache key.

I suggest doing it in a different way: create an ArrayLoader with the template in it (so that getting the cache key works) and set it in Twig. And at the end of the method, reset the original loader in Twig. This way, the original loader is not altered, and you don't need a temporary file