Basic EPiServer Language Switcher

Basic EPiServer Language Switcher

A language switcher is a common task in any EPiServer implementation. In this blog I will show you how to implement a basic language switcher using the EPiServer API.

1aa

First, we will create a basic Header Helper class which will help us with the basic functionality

    public static class HeaderHelper
    {
        public static Injected LanguageBranchRepository { get; }

        // Returns the list of available languages in the site
        public static List GetAvailableLanguages()
        {
            return LanguageBranchRepository.Service.ListEnabled().ToList() ?? new List();
        }

        // Return the current language
        public static LanguageBranch GetCurrentLanguage()
        {
            var currentLanguage = GetAvailableLanguages().Find(x => x.LanguageID ==
            Thread.CurrentThread.CurrentUICulture.ToString());
            return currentLanguage;
        }

        // Return the current page URL based on a specific selected language
        public static string GetCurrentUrlLocalized(PageData currentPage, LanguageBranch selectedLanguage)
        {
            var contentLink = currentPage?.ContentLink;

            if (contentLink != null)
            {
                return UrlResolver.Current.GetUrl(contentLink, selectedLanguage.LanguageID);
            }

            return "/";
        }
    }

Using this helper class we can implement the language switcher easily in the view part

<select name="languages" onchange="location = this.value;">
    <option value="@HeaderHelper.GetCurrentUrlLocalized(Model.CurrentPage, currentLanguage)" selected>
        @currentLanguage.Culture.NativeName.ToTitleCase(currentLanguage.Culture)
   </option>

    @foreach (var language in HeaderHelper.GetAvailableLanguages())
    {
        if (language == currentLanguage)
        {
            continue;
        }

        <option value="@HeaderHelper.GetCurrentUrlLocalized(Model.CurrentPage, language)">
            @language.Culture.NativeName.ToTitleCase(language.Culture)
       </option>
    }
</select>

The current language is not taken into account in the foreach loop, but it is set as the first selected option in the combo box. NativeName returns the language using its proper name. For instance, for Spanish, will display EspaƱol instead of Spanish. Finally, Model.CurrentPage is a PageData that represents the Start Page of the site.

And that is all. With a few lines of code you can create a functional language switcher. I hope it will help someone and as always keep learning !!!

Written by:

Jorge Cardenas

Developer with several years of experience who is passionate about technology and how to solve problems through it.

View All Posts

Leave a Reply