Michael De Keyser
Michael De Keyser

Reputation: 797

Render a template with a specific status code

Since I've read that Chrome is having trouble looping an HTML5 video if the response code isn't 206, I'd like to render my template with a 206 code.

Yet I've not found anywhere how to specify an html code when rendering a template... Did anyone already tried that and succeeded ?

Upvotes: 10

Views: 7746

Answers (4)

Gadelkareem
Gadelkareem

Reputation: 1097

New implementation

protected function renderError(array $parameters, $statusCode = 500)
{
    return $this->render(
        'default/error.html.twig',
        $parameters,
        new Response('', $statusCode)
    );
}

Upvotes: 5

Matteo
Matteo

Reputation: 39460

In the controller you can create and return a Response object with the content and the specified return code, as example:

return new Response(
    $this->renderView('AcmeDemoBundle:Default:video.html.twig', array(
            'param1'    => $param1,
            'param2'     => $param2,
        )),
        206  // return code
);

Hope this help

Upvotes: 7

qooplmao
qooplmao

Reputation: 17759

You can pass a response object with your renderResponse that has the necessary status code.

$response = new Response('', 206);

return $this->renderResponse(
// Or return $this->container->get('templating')
    'AcmeBundle:Video:show.html.twig',
    array('video' => video),
    $response
);

If you do not pass in a Response with your renderResponse one will be generated automatically. If you pass one then it's content is just set to that of the rendered template (as you can see in the code)

Upvotes: 6

Nickolaus
Nickolaus

Reputation: 4835

I think I you at this before you are rendering the template you will get the desired result:

$this->getContext()->getResponse()->setStatusCode(206);    

btw.
The class Symfony\Component\HttpFoundation\Response provides constants for all valid HTTP-states

Upvotes: 1

Related Questions