oasisweng February 2016

How to return Javascript in Symfony2?

Like on Ruby on Rails, you can return Javascript with some prerendering to dynamically update the client site through AJAX.

How do you return Javascript when calling some routes in Symfony2?

For example, when calling updateItemAppearanceAction through \item\{itemId}\update_appearance, return Javascript file updateItemAppearance.js.twig, with array("item"->$item)?

Thank you very much!

Answers


xocasdashdash February 2016

Well if you want to return data for your javascript you could do this in your "updateItemAppearance.js.twig"

var javascriptVar = "{{twigVar|json_encode()|raw('js')}}";

If you're using the JMSSerializer you could do

var javascriptVar = "{{twigVar|serialize('json')|raw('js') }}";

More info: twig docs, jms serializer docs


rvdavid February 2016

You could pass a rendered view to a response object and set the header of updateItemAppearanceAction to text/javascript.

<?php 
namespace OwnerBuilderCentre\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

// example controller. 

class DefaultController extends Controller 
{
    /**
     * @Route("/updateItemAppearance.js", name="default_update_item_appearance_js")
     */
    public function updateItemAppearanceAction()
    {
        $optionalParams = array('some'=>'param');
        $response = new Response($this->renderView('AppBundle:Default:updateItemAppearance.js.twig',$optionalParams));
        $response->headers->set('Content-Type','text/javascript');
        return $response;
    }
}

So now, the javascript you write in updateItemAppearance.js.twig file can be included as a javascript file via the usual means.

<script src="/updateItemAppearance.js"></script>

Post Status

Asked in February 2016
Viewed 2,460 times
Voted 12
Answered 2 times

Search




Leave an answer