views:

15

answers:

1

I'm using a modular system of JavaScript files when working in Rails - basically each view will have its own module in a .js file. My issue comes when I need a dynamic, Rails generated string within my JavaScript, for example translation strings and URLs.

Translations are nicely solved using babilu but I'm still stuck on the generation of URLs. I could write something that looked at the routes in the application and generate JavaScript methods which I could pass stuff like IDs of objects.

An alternative would be to pass in the already-generated URL to any functions I was calling, which sounds messy but could be the most flexible alternative.

+2  A: 

I don't know that there's any truly pleasing way to do this, but one possibility is to have your server-side code write a small <script> block into the page to declare some variables that your packaged Javascript can discover and use.

<script>
  var pageGlobals = {
    interestingURL: <% ... url %>,
    ...
  };
</script>

I've done this to keep track of things like image subdirectories that are determined by customer "syndicate" affiliation. The Javascript code just knows that whenever it needs that for a URL, it can just go look in a global object and pick out a standardized variable.

In my experience there tend to be only a small number of such things to communicate to the canned Javascript, so the <script> block tends not to get out of hand. I've buried mine in a page template so I don't even have to think about it with new pages.

Pointy
Yeah I thought of this, that's what I meant when I said "generate JavaScript methods" in the original comment, I thought of something like: <script type="text/javascript"> var urls = { product: { show: function(id) { return '/product/' + id; } } };</script>
colinramsay