Question

I have a simple js file:

//base.js

...
var url = '/post/' + id + '/comment';
...

I'm using Symfony2 so on the server side all the urls are generated by the Router, and it bugs me that I use hardcoded urls in the js..

Is there a way to make them more dynamic?
Those are the solutions I thought about but I'm not happy with:

  • Defining them in the HTML tags like <div data-url="<?php path('post_comment'); ?>">
  • Defining them in an inline script tag <script language="text/javascript">...</script>

I think that the urls in the js files of some big sites (SO, GitHub, etc.) are hardcoded, am I right?

Was it helpful?

Solution

Friends of Symfony JS Routing Bundle was made exactly for your needs

var url = Routing.generate('some_route_to_expose', { foo: 'bar' });
// url is http://somehost.com/app_dev.php/my_route

The bundle also lets you dump, compile and minify the resulting javascript. Its great!

OTHER TIPS

You should at least minimize namespace pollution by defining all your constant variables inside a configuration object and access it using the property name or getter functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top