FOSRestBundle,似乎无法弄清楚如何使JSON和HTML一起工作 [英] FOSRestBundle, can't seem to figure out how to make JSON and HTML work all together

查看:93
本文介绍了FOSRestBundle,似乎无法弄清楚如何使JSON和HTML一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个博客网站.唯一的实体是Blogposts和Users.我想使用移动电话的JSON GET使这些博客文章可见.但是我还想要一个默认的GET路由,该路由只返回HTML(当然还有CSS).

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

我当然环顾四周,但是除了使网站仅输出JSON外,我似乎找不到更好的教程深入了解FOSRestBundle(但是,我做的事情可能非常错误).

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

现在,当我设置路由时,只能将JSON作为默认路由.我想在URL中执行.json时获得JSON输出,而在默认路由中获得HTML输出.这是我的路线的样子:

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 }

这是MainController.php:

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

到目前为止,当我访问localhost/Symfony/web/app_dev.php/时,我得到了JSON输出.但是我只想在进入localhost/Symfony/web/app_dev.php/.json时获取JSON.我该怎么办?

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.

推荐答案

如果您希望能够通过路由更改格式,请为其添加格式占位符:

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 }

这篇关于FOSRestBundle,似乎无法弄清楚如何使JSON和HTML一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆