简体   繁体   中英

API REST SYMFONY TWIG - AUTH

I'm working on a REST api with symfony, this will perform tasks related to users, authenticate, list, view details, create, etc.

I have already obtained the authentication but I have doubts, mainly with the TWIG views, since I want to centralize these views and not have to maintain them in each system that connects.

What I want to centralize is:

  • View of user detail.
  • View of create / edit user.

Is it okay to place these views in the API? Is it okay to return a full view from the API? How should I do it? Since it is returned in JSON format

I am extending from FOSRestController.

You can make an action which will return JSON or HTML format depending od parameter, so for example you can use JSON format in mobile app and HTML format in some web app.

The possible solution is:

public function userDetailAction($id, $format)
{
    ...
    ...

    if ($format == 'json') {
        $response = new Response(json_encode($data));
        return $response;
    }

    return $this->render('userDetail.twig', array('userData' => $data));
}

or simpler json syntax in Symfony 3

...
if ($format == 'json') {
    return $this->json($data);
}
...

Thanks to @vini comment, I implemented it as follows:

...
$view = View::create(array('user' => $user))
          ->setTemplate("EdcorpUserBundle:User:advance.profile.html.twig")
          ->setFormat('html');

return $this->handleView($view);
}

ref: http://symfony.com/doc/master/bundles/FOSRestBundle/2-the-view-layer.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM