how to turn off the rendering of html responses in twig?

I'm building a RESTful API and want to completly disable HTML rendering. For example if I request /foo/bar without an oAuth Access Token, symfony2 should responses with a 401 json message instead of a 401 html template.

Greetings

有帮助吗?

解决方案

Just don't call the render method : return $this->render('FooBarBundle:Default:index.html.twig');

Instead of this, you can call in your controller :

return new JsonResponse(array(
    'message' => 'Your message here'
), 401);

其他提示

1- Use fosrestbundle. 2- In your config.yml file, put "defaults: {_format: json}" in configuration bundle. 3- In your controller, just throw new UnauthorizedHttpException('optional custom message'). It should do the job.

If you don't wanna use this bundle: use _format: json in your routing.yml.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top