In today's tutorial, you will learn about some approaches that you can use in order to get the current language version of a page. If you are creating a multi-language website then this is very useful. Thanks to Johan Petersson for clarifying a few points :) If you're building a multi-language Episerver website, there will be times when you need to do things task link linking to other pages. When you enable a different language within the editor (see this post for more info), it's very likely that you'll need to get access to a user's current language in code. Luckily using Episerver CMS this is fairly simple, read on to find out how!
Getting Access To The Current Users Language
First, if you want to get access to the current user's languages, you can use this technique:
When I build an Episerver website, I prefer to follow dependency injection rather than using static references within my code. If you want to do the same, I suggest that you create a custom globalization wrapper, like this:
The interface for this class looks like this:
Some readers may not see the architectural benefit from wrapping static helpers, however, following this pattern will help to make your code testable. For the haters of unit testing, I recommend you give it a try 😊😊😊
What Are Episerver GlobalizationSettings?
There are several scenarios where you might need to know more information about the current pages language setting. For example, your website might be configured to work with several languages, e.g. a UK version and a French version. A user visits your site, however, the page they visit hasn't been set up in the CMS with French translations, what do you do?
Episerver provides fallback languages for these types of scenarios. This is handy as it will mean that the page will render some content rather than nothing. In these instances, instead of getting the pages fallback content, you might want to get information about what language the page supports, so you can decide in code what to do. Episerver provides this ability via the
GlobalizationSettings class. The
GlobalizationSettings properties look very similar to the
Thread.CurrentThread properties and it is very easy to get them confused. These properties define in
GlobalizationSettings map to the user's preferences. The
Thread.CurrentThread properties reference the current thread state. You can use
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
EPiServerFramework section within your
web.config, you can notice a
fallbackCulture. This setting can be used to apply a default global value. This covers most the basics that you will need to understand in order to work will multi-languages in code. Happy Coding 🤘