Skip to content

Instantly share code, notes, and snippets.

@snirgel
Created August 16, 2012 15:14
Show Gist options
  • Save snirgel/3370902 to your computer and use it in GitHub Desktop.
Save snirgel/3370902 to your computer and use it in GitHub Desktop.
Returning rendered template as JSON with Symfony2 and Twig
class YourController extends Controller
{
public function your_returnAction(){
$lReturn = array();
//use renderview instead of render, because renderview returns the rendered template
$lReturn['html'] = $this->renderView('Bundle:Controller:yourtemplate.html.twig');
return new Response(json_encode($lReturn), 200, array('Content-Type'=>'application/json'));
}
}
@DimaSerikov
Copy link

DimaSerikov commented Mar 22, 2018

use Symfony\Component\HttpFoundation\JsonResponse;

    {
        $page = $request->get('page');
        $from = $page * BlogPost::POST_PER_PAGE;

        $posts = $this->getDoctrine()->getRepository('AppBundle:BlogPost')->getPosts(BlogPost::POST_PER_PAGE, $from);

        if ($posts) {
            $result = $this->renderView('blog/index.html.twig', [
                'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
                'posts' => $posts,
            ]);

            return new JsonResponse(['success' => true, 'articles' => $result]);
        } else {
            return new JsonResponse(['success' => false, 'posts' => []]);
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment