FOSRestBundle, can't seem to figure out how to

2019-07-27 08:43发布

问题:

I have a blog site. The only entities are Blogposts and Users. I want to make these blogposts visible with json GETs for mobiles. But I also want a default GET route which just return the HTML (and CSS ofcourse).

Of course I've looked around, but I can't seem to find a nice tutorial that goes a bit deeper into FOSRestBundle other than making the website only output JSON (But ofcourse, I could be doing stuff horribly wrong).

Right now, when I setup my routes, I can only get JSON as a default route. I want to get JSON output when I do .json in the URL, and HTML when default route. This is how my route looks:

_welcome:
    pattern: /
    defaults: { _controller: TestTestingBundle:Main:homepage, _format: json }

And this is the MainController.php:

<?php

namespace Test\TestingBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;  

class MainController extends Controller
{
    public function homepageAction()
    {
        $latestposts = $this->getLatestBlogs();
        $posts = $this->trimContent($latestposts);

        $view = View::create(array('lastblogs' => $posts))
                    ->setStatusCode(200)
                    ->setEngine('twig')
                    ->setTemplate(new TemplateReference('TestTestingBundle', 'Index', 'index'))
                    ->setData($latestposts);

        return $this->get('fos_rest.view_handler')->handle($view); 
    }
}

As of now, when I visit localhost/Symfony/web/app_dev.php/ I get the JSON output. But I only want to get JSON if I go to localhost/Symfony/web/app_dev.php/.json. How should I do this?

If you need more code, please comment.

回答1:

If you want to be able to change the format through your route, add a placeholder for the format to it:

_welcome:
    pattern: /.{_format}
    defaults: { _controller: TestTestingBundle:Main:homepage }