Run
Run

Reputation: 57266

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:

$response->getBody()->write(json_encode($data));

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?

Upvotes: 0

Views: 156

Answers (1)

Rob Allen
Rob Allen

Reputation: 12778

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);

Upvotes: 2

Related Questions