How to Generate Routing URLs in JavaScript

How to Generate Routing URLs in JavaScriptΒΆ

If you're in a Twig template, you can use the same path() function to set JavaScript variables. The escape() function helps escape any non-JavaScript-safe values:

  • Twig
    1
    2
    3
    <script>
    var route = "{{ path('blog_show', {'slug': 'my-blog-post'})|escape('js') }}";
    </script>
    
  • PHP
    1
    2
    3
    4
    5
    6
    7
    8
    <script>
    var route = "<?php echo $view->escape(
        $view['router']->path('blog_show', array(
            'slug' => 'my-blog-post',
        )),
        'js'
    ) ?>";
    </script>
    

New in version 2.8: The path() PHP templating helper was introduced in Symfony 2.8. Prior to 2.8, you had to use the generate() helper method.

But if you actually need to generate routes in pure JavaScript, consider using the FOSJsRoutingBundle. It makes the following possible:

1
2
3
4
5
<script>
var url = Routing.generate('blog_show', {
    'slug': 'my-blog-post'
});
</script>

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.