6

There is a use case that is quite popular when building international web application:

There are localized templates for each culture, with name convention like 'en_US/name.html', 'ru_RU/name.html' etc.

User's locale setting could be get only after user logged (or user can select locale).

So the best option that I found is to provide localization value using DI (so it could be updated form anywhere - or when I recieve response from backend with user config, or when user select something).

But routing could be configured only in configuration step, where 'values' could not be injected. So you can't inject locale config and add templateUrl according to that value.

Here is a Plnkr example do illustrate my solution.

Only other solution I see, is to modify private array of routes (using $route.routes[]), but it sounds like ugly hack.

Is there are other solutions to implement this common use case of using localized templates?

Valentyn Shybanov
  • 19,331
  • 7
  • 66
  • 59

1 Answers1

1

There might be ways to do this as you want, like overriding templateCache instead of modifying routing but I'm going to approach this issue differently.

In your approach, as your site grows it would be very difficult to maintain (at least) 2 copies of templates. If you support more languages, then you'd be in trouble much shorter.

I'd create a service which holds dictionary like objects for languages.

angular.module("myApp", [])
       .factory("Internationalization", function () {
           var dict: {
               en_US: {
                   hello: "Hello,"
               },
               fr_FR: {
                   salut: "Salut,"
               }
           };
           var get = function (locale, key) {
               return formatdict[locale][key];
           }
           return {get: get};
       });

Then you can inject the service in the controller and attach it to scope.

This should help you getting started, you might want to check this out if you want string.format support.

Community
  • 1
  • 1
Umur Kontacı
  • 35,403
  • 8
  • 73
  • 96
  • 1
    Actually all copies of templates in my project are generated at backend using default Razor internationalization approach. So actually I have one template with content like `
    @Hello
    ` and XML files with translations. Then we'd wrote hanlder that will change culture using URL, so to get english translated template you need to get it by url `/en_US/index.html` and cached. This way it works much much faster (as i18n is done on server once and then result cached) and easy to maintain. The only problem is with TemplateURL...
    – Valentyn Shybanov Jan 20 '13 at 18:54