In this tutorial, you will learn how to work with languages in your Umbraco website, all through code. It is possible to configure and work with languages manually within the Umbraco backend, however, if you are doing content migrations between different environments (like staging/production), having to manually copy and configure settings across environments is likely to result in bugs occurring. If you have multiple developers working on a project, forcing each team member to manually update their local database wastes 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 language data to disk is 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

LocalizationService

To get and add new languages you will be using the Umbraco LocalizationService. You can access the LocalizationService via the application context. Most of the code that I have found online 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 any dependencies I require as constructor parameters. 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 custom service and inject the ILocalizationService interface. The code to do this can be seen below:

If you follow this pattern you can then apply a SOLID methodology. Next, let's write some code to query all the active languages that have been set inside Umbraco!

Getting All Existing Languages

To get all the enabled languages within the CMS you can use the GetAllLanguages() method, like so:

You can render that list using this code:

We now have a way to access and render the language data. Step one accomplished!

Adding New Languages Using 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! Happy Coding 🤘