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?

有帮助吗?

解决方案

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!

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top