title: Dynamic (i18n) links using expressjs and jade
body: <p>I am using expressjs and i18n-node (https://github.com/mashpie/i18n-node). It's working, except for elegant linking. What I have now is this:</p>
  
  <pre><code>app.all(/^\/(\w{2}\/)+(\w*)?/, function(req, res, next) {
      var lang = req.params[0];
      var type = req.params[1];
  
      req.url = req.url.replace(lang, "");
  
      if(type !== 'javascript' &amp;&amp; type !== 'img' &amp;&amp; type !== 'css') {
        i18n.setLocale(lang.slice(0, 2));
      }   
      next();
  });
  </code></pre>
  
  <p>(I want /foo as well as /en/foo to work). If the language is not specified in the url, the headers are checked, and if not, it defaults to English. By the way, my solution seems less than ideal (I have to make manual checks to see if it is not static content), so if any of you have a better solution I am all ears.</p>
  
  <p>Now, my real problem is making links to internal content. If a user is here: "/en/foo", a "/bar"-link should actually be "/en/bar". I am using jade (for no particular reason other than that it was the default, again open to suggestions..)</p>
  
  <p>I tried adding a helper function to Jade:</p>
  
  <pre><code>app.helpers({
    __i: i18n.__
    ,__n: i18n.__n
    ,link_to: function(link, text) {
      //TODO: how to get request here?
      // this should be defined to the absolute base path
      var baseUrl = "/";
      // only append locale if it is part of the existing url!
      var locale = i18n.getLocale();
      return '&lt;a href="' + baseUrl + locale + '/' + link + '"&gt;' + text + '&lt;/a&gt;';
    }
  });
  </code></pre>
  
  <p>.. but it has many problems:</p>
  
  <ol>
  <li>How do I get the base url? So for instance, if the site is located at "http://www.example.com/foo/bar", and I link to "testLink", link_to will generate "http://www.example.com/foo/bar/testLink", instead of "/testLink" or "http://www.example.com/testLink" etc..</li>
  <li>How do I determine if the url contains a localization parameter or not? I don't want to append a localization-parameter to the link if it is unnecessary.</li>
  <li>The function itself is not great; In Jade it is called like this: := link_to("testUrl", "some link description"). I would rather do something like this:
  link_to(href="someUrl")
    div some more jade code</li>
  <li>(minor) The HTML is written directly in the JS</li>
  </ol>
  
  <p>What is the preferred way to do this? I've been searching and searching, but unable to find a good answer..</p>
  
  <p>This is actually also a general question; i.e how do you link to other internal content, like the link_to in Rails. Simply doing a(href="someAction") is not good enough, as you want it to generate absolute URLs so that the pretty URLs do not break static content links.</p>
  
  <p>Thanks!</p>