teelou teelou - 9 months ago 31
Twig Question

Twig - cache json?

I am using Slim Framework with Twig. The cache in Twig works ok when I output html. But it does not work when I output json:


return $response->withHeader('Content-type', 'application/json');

My Twig setting in the Slim container:

$twig = new Twig_Environment($loader, array(
'cache' => 'cache/',

Obviously it does not cache json at all. Is it possible to have Twig cached json then?

Any ideas?

Answer Source

Twig's cache is required because you are writing files in a special language that needs translating to PHP. If you look at the files in the cache/ directory, you'll see that they are your Twig files converted to PHP.

JSON is not a special language and PHP has built-in conversation from array to JSON (json_encode) and so there is no need to create a PHP version and hence there is no need for a cache directory for JSON output.

Finally, as an aside, in Slim, you can create a JSON output with:

return $response->withJson($data);