Search code examples
backbone.js

URL rewrites - routing in Backbone


I have a www.example.com domain, and I need it to make it URL friendly. That domain need to be in multilanguage, like this:

http://{language}.example.com/restufullurls

How is that achievable in Backbone/Marrionette, only using routes?


Solution

  • First make a config file somewhere:

    var config = {
       lang: 'en',
       domain: 'example.com'
    };
    

    Then make a base model that will rewrite the url of all models. What this does is rewrites the URL you specify in a model by appending the correct URL from the config file:

    var BaseModel = Backbone.Model.extend({
       initialize: function(){
          this.url = 'http://' + config.lang + '.' + config.domain + '/' + this.url;
       }
    });
    

    Then every time you need a new Model, you can extend the Base

    var SomeModel = BaseModel.extend({
       url: 'some/rest/url'
    });
    

    If you need to switch the language just do

    config.lang = 'new-language';
    

    If you would like to use the same URL as the file is being served from just do:

    var BaseModel = Backbone.Model.extend({
       initialize: function(){
          this.url = window.location.origin + '/' + this.url;
       }
    });