I am currently working on developing a multilingual website using AngularJS. While providing translations in templates seems straightforward, I am facing challenges when it comes to implementing proper multilingual routes using UI-Router. Unfortunately, I have not been able to find suitable examples to guide me through this process.
The goal is to easily scale the website when adding new languages. For example, the structure of routes for two languages would look like:
/en
/en/products
/en/products/green-category
/en/products/green-category/green-product-1
/cs
/cs/produkty
/cs/produkty/zelena-kategorie
/cs/produkty/zelena-kategorie/zeleny-produkt-1
While product categories are hardcoded, products are dynamically loaded from the database.
My attempted solution looks something like this (excluding product categories as they follow a similar structure to 'products', just one level deeper):
$stateProvider.state('product', {
url: '/{lang:' + Translate.getLangs() + '}/{products:' + Translate.getRouteVariants('products') + '}/{productSlug}',
templateUrl: 'app/product.html',
resolve: {
product : function($stateParams){
return Data.products.get( Data.products.deslug($stateParams.productSlug, $stateParams.lang), $stateParams.lang );
}
}
});
And in controller / template:
$scope.productLink = function(id) {
return {
lang:$rootScope.lang,
products:Translate.getRoute('products', $rootScope.lang),
productSlug:Data.products.slug(1, $rootScope.lang)
};
}
<a ui-sref="product(productLink(1))">Green product 1</a>
Where
Translate and Data are providers
Translate.getLangs() -> 'en|cs'
Translate.getRoute('products', lang) -> 'products' or 'produkty' depending on language
Translate.getRouteVariants('products') -> 'products|produkty'
Data.products.slug(productId, lang) -> returns productSlug from model
Data.products.deslug(productSlug, lang) -> returns productId from model
Data.products.get(productId, lang) -> loads data
This current method of handling the language could be improved (likely within the Translate provider).
The issue of preventing cross-language URLs such as '/en/produkty' is a major concern. /edit: I might consider using $stateChangeStart to validate whether all parameters match one language and if not, redirect to the top-level state.
This whole solution may not be the most elegant (given my beginner status with Angular), so any insights or guidance on this matter would be greatly appreciated.
Thank you.