Search code examples
restsymfonyfosrestbundle

Controller not rendering the template


I am using FOS bundle to implement REST API in symfony.

I have a controller called termsController in which i have implemented all the routes for REST API.

The routes for put,get,post and delete return an array but i want the function newTermAction (whose route would be /terms/new ) to render a template.

That is this route should direct to the form from where il make the post call

But the template is not getting rendered and the output is the raw html code

Here is the function

public function newTermsAction()
  {

    return $this->render('default/termForm.html.twig');
  }

Config.yml file

sensio_framework_extra:
    view:   {   annotations: false }
    router: {   annotations: true }

fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener: true
    view:
        view_response_listener: 'force'
        formats:
            xml: true
            json : true
        templating_formats:
            html: true
        force_redirects:
            html: true
        failed_validation: HTTP_BAD_REQUEST
        default_engine: twig
    routing_loader:
        default_format: json

I have tried using this but this is not working

$view = $this->view()
            ->setTemplate("TermsBundle:Default:termForm.html.twig");
    return $this->handleView($view);

Error : Attempted to call an undefined method named \"view\" of class

Solution

  • Try something like that:

    public function newTermsAction(){
        $view = $this->view(null, 200)
            ->setTemplate('default/termForm.html.twig')
        ;
    
        return $this->handleView($view)
    }
    

    You may have to tweak some config. Take a look at this part of the docs for more details.

    EDIT: The issue was that the Controller did not properly inherit the FOSRestController, this is the correct way to do it.

    In addition, don't forget to add the html format at the end of the request, or the Controller will try to render the default format set in the config, e.g. :

    terms/new.html