Internationalization and Routing: adding the language code (en,de,fr) inside URLs |
[eluser]Michael Ekoka[/eluser]
language internationalization i18n routing For those interested in having the current language in the url like this: http://www.mysite.com/en/my_controller/my_action/var1/var2 I have been playing around with routing and hopefully the time I spent will be worth your while. You first need to follow a couple of steps in your application's config/routes.php: 1-) You first need to set a regex for the language code that will be prepended to request urls other than the index page. The regex covers the following criteria: - the language code should be optional - it should be composed of 2 alphabetical characters - if added, it must be followed by a slash e.g. The following urls should point to the same route: http://www.mysite.com/en/controller/action/var1/var2 http://www.mysite.com/controller/action/var1/var2 In your routes.php file insert this: Code: // routes.php 2-) You also need a slightly different regex for the language code optionally appended to the index url (www.mysite.com/en) . The criteria covered by that regex: - the language code should be optional - it should be composed of 2 alphabetical characters - if appended to the index, the language code has an optional trailing slash e.g. the following url should all point to the same route http://www.mysite.com/ http://www.mysite.com/en http://www.mysite.com/en/ still in routes.php insert this: Code: // routes.php 3- Now lets set some routes in routes.php: Code: /* routes for controllers */ 4- Now in your controller if you want to know which language has been requested, do this: Code: $lang_code = $this->uri->segment(1); Some gotchas: - Verify the length of $lang_code. In the case that it is not 2 characters long, you can assume that $this->uri->segment(1) did not in fact return the language code, but rather the next item after it. This means that the request had no language code : e.g. http://www.mysite.com/somerequest. Make sure to then reset $lang_code to a default language. - If $lang_code is 2 characters long, check its value against an actual list of supported language codes, in case a user sends you a request such as http://www.mysite.com/fr/somerequest, and you didn't prepare any fr translations. Here too you can use some logic to default any non supported language to a default. Your application can now be accessed in 2 ways: http://www.mysite.com/{lang_code}/contro...ar1/value1 and http://www.mysite.com/controller/action/var1/value1 I'm still testing all this in my own app, please contribute if you find something odd or useful. |
Welcome Guest, Not a member yet? Register Sign In |