Php Symfony 3+;FOSRestBundle返回模板/查看为json
我希望我以一种好的方式发布这个问题。 我试图在谷歌和symfony文档中找到答案,但没有什么对我有帮助——可能是因为我的symfony技能(我不知道这个框架——我正在努力学习:)) 我的目标是从数据库中获取文章(我知道怎么做,所以我在代码中跳过了这个操作,准备了一个视图并以json的形式返回——我可以使用FOSRestBundle 我的symfony版本是3.3.9,FOSRestBundle:2.2.0 我的问题是,我有一个具有以下配置的rest api项目:Php Symfony 3+;FOSRestBundle返回模板/查看为json,php,json,symfony,fosrestbundle,Php,Json,Symfony,Fosrestbundle,我希望我以一种好的方式发布这个问题。 我试图在谷歌和symfony文档中找到答案,但没有什么对我有帮助——可能是因为我的symfony技能(我不知道这个框架——我正在努力学习:)) 我的目标是从数据库中获取文章(我知道怎么做,所以我在代码中跳过了这个操作,准备了一个视图并以json的形式返回——我可以使用FOSRestBundle 我的symfony版本是3.3.9,FOSRestBundle:2.2.0 我的问题是,我有一个具有以下配置的rest api项目: fos_rest: vi
fos_rest:
view:
default_engine: twig
view_response_listener: force
force_redirects:
html: true
# xml: true
formats:
jsonp: true
json: true
xml: true
rss: false
templating_formats:
html: true
json: true
mime_types:
json: ['application/json', 'application/x-json', 'application/vnd.example-com.foo+json']
rss: 'application/rss+xml'
jpg: 'image/jpeg'
png: 'image/png'
jsonp_handler: ~
body_listener: true
param_fetcher_listener: force
allowed_methods_listener: true
access_denied_listener:
json: true
format_listener:
rules:
- { path: ^/api/v1, priorities: [html, json, xml], fallback_format: json, prefer_extension: false }
routing_loader:
default_format: ~
exception:
codes:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
messages:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': true
service:
view_handler: fos_rest.view_handler.default
我的控制器操作看起来:
/**
* @ViewAnnotation()
*/
public function getArticleAction()
{
$data = [
'any' => 'any'
]; // get data, in this case list of users.
$view = $this->view($data, 200)->setTemplate('MyBundle:Article:getArticles.html.twig');
return $this->handleView($view);
}
问题是,此代码返回html而不是json。此外,对于我不想呈现视图的其他控制器,我有以下消息:
Unable to find template "" (looked into: /var/www/html/app/Resources/views, /var/www/html/vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form).
如果我尝试更改config.yml(fos_rest部分),我的api将返回:
{“任何”:“任何”}
我可以使用JsonResponse并通过跳过FOSRestBundle来做我想做的事情,但我希望理解并能够使用FOSRestBundle。
有谁能帮我一步一步地写下我是如何达到我想要的,或者给我什么建议,哪里出了问题