0

I'm trying to do something pretty simple.

Here's the scenario: I have a whole site working great with pushstate enabled browsers. The site works off the basis that the language is the "actual page" for instance:

/en/whatever/etc  = index.en.php with  with english headers and encoding & tweaks
/ar/whatever/etc  = index.ar.php with  with arabic headers and encoding & tweaks
/ru/whatever/etc  = index.ru.php with  with russian headers and encoding & tweaks

It's really slick and works nicely with pushstate as I mentioned. The problem is when I try to use the same router code with the hash alternative.

Backbone's router seems to want to do this:

/#/en/whatever/etc = bad because it's not based correctly
/#/ar/whatever/etc = and so on

what I want it to do is:

/en/#whatever/etc
/ar/#whatever/etc
/ru/#whatever/etc
..and so on

or even:

/en/#/whatever/etc
/ar/#/whatever/etc
/ru/#/whatever/etc
..and so on

But i can't find a way without tweaking backbones source to implement this. I'm kind of against changing backbone.js unless I really have to because of the futureproofing factor.

Anyone have any thoughts?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Alex
  • 3,732
  • 5
  • 37
  • 59

1 Answers1

5

You need to use the root option in the Backbone History object:

Quote the docs:

If your application is not being served from the root url / of your domain, be sure to tell History where the root really is, as an option: Backbone.history.start({pushState: true, root: "/public/search/"})

You're going to have to do some code that happens on your landing page that looks at what language they're using, and then sends them to /[LANG CODE]/. Then on your server, you just map requests for /[LANG CODE]/ to your .html file.

In your HTML file look at the location.pathname variable, strip off the first /[LANG CODE]/ part and use that as your root value for the options hash.

var lang = "/"+_.first(location.pathname.split('/')+"/";
Backbone.history.start({pushState: true, root: lang}); // if you're using pushState, otherwise omit or set to false

This will cause your URLs to be:

/en/#whatever/etc
/ru/#whatever/etc
tkone
  • 22,092
  • 5
  • 54
  • 78