This article will hopefully be short and sweet. If you're building a multi-language Episerver website, there will be times when you need to do things like creating URLs to pages within, or, linking to assets like images. When you enable a different language within the editor (see this post for more info), then it's also very likely that you'll need to get access a user's current language in code. In today's guide, I'm going to cover the different ways that you can achieve this. Thanks to Johan Petersson for clarifying a few points :)
Getting Access To The Current Users Language
First, if you want to get access to the current user's languages, you can still use the out-of-the-box method, like so:
When I build an Episerver website, I prefer to use dependency injection rather than just use static references within my code, as it makes testing a lot more complex. If you want to make your life a little easier, I suggest that you create a globalization wrapper, like this:
With an interface that might look like this:
Some readers may not see the architectural benefit from wrapping requests, but, following this pattern will help you decouple your code, so for the haters of unit testing, I recommend you give it a try :)
What Are Episerver GlobalizationSettings?
There are several other language scenarios that exist, where you might need to know more information about the current page, rather than the current user languages Say, your website might be configured to work with several languages, a French user visits your site, but that page doesn't have a French translation, what do you do?
Episerver provides fallback languages for these types of scenarios. In these instances, instead of getting the pate you might want to get information about what language it supports instead.
Episerver provides this function via the GlobalizationSettings class. The GlobalizationSettings properties look very similar to the Thread.CurrentThread properties and it's very easy to get them confused (see the comments below for proof :P). You can use the GlobalizationSettings like so:
The output of these properties might look very similar to the current thread languages, however, if the current page doesn't have a translation, the GlobalizationSettings will also provide you with the fallback language to get instead. If you look within the EPiServerFramewotk section within your web.config, you can notice a fallbackCulture property, asides from setting falback preferes within the editor y
To access the current language, you can use the normal .NET current thread properties. These properties should not be confused with the GlobalizationSettings properties. These properties define the users' preferences, rather than the current language.