Ruehri
Ruehri

Reputation: 858

Pass language parameters into jade links

I have a multi-language website which uses language identifiers in the hyperlinks e.g., /en/contact for the English contact page and /de/contact for a German contact page.

If I cross link on my page, for example from the index page to the contact page, how can I "pass" the language part in my hyperlink? Depending on if I am on /en/index or on /de/index, the hyperlink needs to either point to /en/contact or /de/contact.

I am using Express + Jade. There is one jade template for both languages which needs to set the link dynamically depending on if the user is on an /en or /de page.

Thanks a lot in advance!

Upvotes: 0

Views: 115

Answers (2)

Ryan
Ryan

Reputation: 5973

This is the simplest example I can think of. Use a middleware function to inspect the request and pull out the language, then set that as a variable that will be available to your template. You may be able to use more of a global middleware but this example shows it on a single route:

app.use('/:userLang/contact', i8n, users);

function i8n(req, res, next) {
  var supportedLanguages = ['en', 'de'];
  var defaultLang = 'en';
  var pathLang = req.params.userLang;

  // default to en if a user trys a language that isn't supported
  // another(possibly better) option would be to 404 or 301 to the en version
  res.locals.userLang = (supportedLanguages.indexOf(pathLang) > -1) 
                          ? req.params.userLang : defaultLang;
  next();
}

Once the above code is in place links in your template could look like this:

a(href="/#{userLang}/contact) Contact Page

Upvotes: 1

owais
owais

Reputation: 4922

being at contact page you can send user to english index page assuming your are on english contact page

a(href="/en/index")

Upvotes: 0

Related Questions