How to Generate Routing URLs in JavaScript
Edit this pageWarning: You are browsing the documentation for Symfony 3.0, which is no longer maintained.
Read the updated version of this page for Symfony 6.3 (the current stable version).
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:
1 2 3
<script>
var route = "{{ path('blog_show', {'slug': 'my-blog-post'})|escape('js') }}";
</script>
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>
But if you actually need to generate routes in pure JavaScript, consider using the FOSJsRoutingBundle. It makes the following possible:
1 2 3
var url = Routing.generate('blog_show', {
'slug': 'my-blog-post'
});