我正在尝试使用Symfony2和FOSRestBundle来提出一个REST框架,但我失败得很痛苦。
我做了以下工作:
在我的deps文件中:
[FOSRest]
git=git://github.com/FriendsOfSymfony/FOSRest.git
target=fos/FOS/Rest
[FOSRestBundle]
git=git://github.com/FriendsOfSymfony/FOSRestBundle.git
target=bundles/FOS/RestBundle
[JMSSerializerBundle]
git=git://github.com/schmittjoh/JMSSerializerBundle.git
target=bundles/JMS/SerializerBundle在我的app/config.yml中
fos_rest:
view:
formats:
rss: true
xml: false
templating_formats:
html: true
force_redirects:
html: true
failed_validation: HTTP_BAD_REQUEST
default_engine: twig
sensio_framework_extra:
view:
annotations: false在我的控制器中:
namespace Rest\WebServiceBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;
class DefaultController extends Controller
{
public function indexAction($name)
{
$view = View::create()
->setStatusCode(200)
->setData($name);
return $this->get('fos_rest.view_handler')->handle($view);
}
}当我转到网址:http://local.symfony.com/web/app_dev.php/hello/test
我得到了:
Unable to find template "".
500 Internal Server Error - InvalidArgumentException
2 linked Exceptions: Twig_Error_Loader » Twig_Error_Loader文档对我来说似乎很混乱,我无法继续。我想要的就是能够将一个数据数组传递给控制器,然后返回一个JSON格式。有人能帮帮忙吗?
发布于 2012-05-14 03:15:43
在config.yml的formats部分,您必须启用json格式并禁用其他格式,并在路由中将默认的_format值设置为json。e.g
# app/config/config.yml
fos_rest:
view:
formats:
json: true
rss: false # removing them will also work
xml: false
#.......
#bundle/routing.yml
route_name:
pattern: /route
defaults: { _controller: Bundle:Controller:Method, _format:json }或者,您可以在控制器中执行以下操作
$view->setFormat('json');还可以查看文档中给出的示例链接。
https://stackoverflow.com/questions/10573764
复制相似问题