In this tutorial, you will learn how to work with languages in your Umbraco website, all through code. It is possible to work with languages manually within the Umbraco backend, however, any manual content import can burn a lot of your precious project time. If you have multiple developers working on a project and if each person has to manually update languages you waste time. The more people on the team, the more time wasted. This is one of the reasons why automating it makes sense.
Writing the code to get and save languages is fairly quick and easy, so it makes more sense to write the code once and save some time. If this sounds good to you, read on
To get and add new languages you will be using the Umbraco LocalizationService. You can access the LocalizationService via the application context. If you Google around the code around the location service, most of the code has been written in a way that breaks SOLID principles, as the application context is a static class.
When I build any C# website I like to follow a SOLID methodology, so I like to work against interfaces and inject my dependencies from a constructor. The ApplicationContext does not follow SOLID principles, as it is a static class. The good news is that the LocalizationService is written to an interface, so I suggest that when you write a class and inject the ILocalizationService interface and build to that, like so:
If you follow this pattern you can then apply a SOLID methodology. Next, let's write some code to query all the languages set in your website
Getting All Existing Languages
To create a language picker, you will need to get all the languages defined within Umbraco. You can use this using the GetAllLanguages() method, like so:
You can then render the available languages set-up within Umbraco using this code:
Adding A New Languages into Umbraco through Code
As well as getting all the languages via code, you can also add new languages into Umbraco, like so:
Now you know how to read and write new languages into Umbraco, enjoy!