0

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!

2 Answers 2

6

Within the action method called updateItemAppearanceAction:

  1. Create a Rendered view
  2. Instantiate a Response object, passing the rendered view in the Constructor.
  3. Set the Content-Type in the Response Header of the Response Object's instance to text/javascript.

    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');
            $renderedView = $this->renderView('AppBundle:Default:updateItemAppearance.js.twig'); // 1.
            $response = new Response($renderedView, $optionalParams)); // 2.
            $response->headers->set('Content-Type','text/javascript'); // 3.
            return $response;
        }
    }

As a result, the javascript you write in updateItemAppearance.js.twig file can be embedded as a javascript file via the usual means.

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

Or using the twig path helper.

<script src="{{ path('default_update_item_appearance_js') }}"></script>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.