Walkthrough: Creating a language switcher component

Version: 21.x

This topic describes how to implement a language switching component in an ASP.NET Core rendering host, using built-in ASP.NET Core localization and routing functionality.

Note

This walkthrough assumes you are configuring routing endpoints using the MapSitecoreLocalizedRoute extension or otherwise using the sitecoreRoute route value to indicate the item path to request from the Layout Service and the culture route value to indicate the desired language. For further information, see Sitecore Rendering Engine.

This walkthrough describes how to:

Create the View component

This example uses an ASP.NET Core view component to encapsulate the logic and presentation of the language switcher. You can then add the view component to the relevant location in your application.

To create the view component:

  1. Create and start an ASP.NET Core based solution as described in the Getting Started guide.

  2. In Visual Studio, in the rendering project, open the Startup.cs class.

    Note

    Some changes are required in this class to make the ASP.NET Core RequestLocalizationOptions available to our language switcher through dependency injection.

  3. In the ConfigureServices method, add the following localization configuration registration, which enables three languages, in this example, German, English, and Japanese, as well as the Sitecore URL-based culture resolution:

    RequestResponse
    // You need to configure localization options here so you can access them in your language switcher component
    services.Configure<RequestLocalizationOptions>(options =>
    {
        // If you add languages in Sitecore that this site/rendering host should support, then add them here.
        var supportedCultures = new List<CultureInfo> { new CultureInfo(_defaultLanguage), new CultureInfo("de-DE"), new CultureInfo("ja-JP") };
        options.DefaultRequestCulture = new RequestCulture(_defaultLanguage, _defaultLanguage);
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;
    
        // Resolve culture through the standard Sitecore URL prefix and query string (sc_lang).
        options.UseSitecoreRequestLocalization();
    });
    
  4. In the Configure method, remove the existing call to app.UseRequestLocalization and replace it with a simpler one:

    RequestResponse
    // Enable ASP.NET Core localization, required for Sitecore content localization.
    app.UseRequestLocalization();
    
  5. In the Models folder of the rendering project, add a new model class for the language switcher. This class outputs current and available languages. Add the following code in the class:

    RequestResponse
    using System.Collections.Generic;
    using System.Globalization;
    
    namespace MyProject.Models
    {
        public class LanguageSwitcherModel
        {
            public CultureInfo CurrentUICulture { get; set; }
            public List<CultureInfo> SupportedCultures { get; set; }
            public string CurrentSitecoreRoute { get; set; }
        }
    }
    
  6. Create a new folder in the rendering project called ViewComponents, and create a new View Component class inside the folder. This class populates the model based on the configured languages, current language, and the current route. Add the following code in the class:

    RequestResponse
     using MyProject.Models;
     using Microsoft.AspNetCore.Builder;
     using Microsoft.AspNetCore.Localization;
     using Microsoft.AspNetCore.Mvc;
     using Microsoft.Extensions.Options;
     using System.Linq;
     using System.Threading.Tasks;
    
     namespace MyProject.ViewComponents
     {
         public class LanguageSwitcherViewComponent : ViewComponent
         {
             private readonly IOptions<RequestLocalizationOptions> _localizationOptions;
    
             public LanguageSwitcherViewComponent(IOptions<RequestLocalizationOptions> localizationOptions)
             {
                 _localizationOptions = localizationOptions;
             }
    
             public async Task<IViewComponentResult> InvokeAsync()
             {
                 var cultureFeature = HttpContext.Features.Get<IRequestCultureFeature>();
                 var languageSwitcherModel = new LanguageSwitcherModel
                 {
                     SupportedCultures = _localizationOptions.Value.SupportedCultures.ToList(),
                     CurrentUICulture = cultureFeature.RequestCulture.Culture,
                     CurrentSitecoreRoute = this.HttpContext.Request.RouteValues["sitecoreRoute"]?.ToString() ?? ""
                 };
                 return View(languageSwitcherModel);
             }
         }
     }
    
  7. In the rendering project, create a new folder path for the component's view, Views/Shared/Components/LanguageSwitcher. Create a Razor View within the folder called Default.cshtml. This view renders our language switcher using the model. Add the following code in the view:

    RequestResponse
    @model LanguageSwitcherModel
    
    <ul id="language-switcher">
    @foreach (var culture in Model.SupportedCultures)
    {   
        <li>
        @if (Model.CurrentUICulture.Name == culture.Name)
        {
            <strong>@culture.DisplayName</strong>
        }
        else
        {
            <a asp-route-culture="@culture.Name" asp-route-sitecoreRoute="@Model.CurrentSitecoreRoute">@culture.DisplayName</a>
        }
        </li>
    }
    </ul>
    
  8. In the Views/_ViewImports.cshtml View, add the following line to enable the use of custom View Components from this project as Tag Helpers:

    RequestResponse
    @addTagHelper *, MyProject
    
  9. Add the language switcher to Views/Default/Index.cshtml (the default View) under the Sitecore logo:

    RequestResponse
    <div id="Header">
        <img src="/img/sc_logo.png" alt="Sitecore" id="scLogo">
        <vc:language-switcher></vc:language-switcher>
    </div>
    
  10. Refresh the rendered site (www.myproject.localhost) to see your changes. You can switch languages, but there is no content available in, for example, German or Japanese yet.

Important

If you encounter an error, check the rendering host logs for compilation errors. In PowerShell, type the following: docker-compose logs -f rendering.

Add Sitecore languages and content

To add Sitecore languages and content:

  1. Log in to the CM environment (cm.myproject.localhost) and open the Content Editor from the Launchpad.

  2. Under /sitecore/system/languages, add the languages you want, for example, German (Germany) and Japanese (Japan). This process creates language items for de-DE and ja-JP.

  3. Navigate to the /sitecore/content/MyProject/Home/Content content item and create language versions for these new languages, and populate the Title field with relevant content, for example:

    • German: Hallo!

    • Japanese: こんにちは

  4. Publish the language additions and content changes.

  5. Go to your rendered site. You can now see the language-specific content when you switch languages.

Configure serialization for language items (optional)

In a production solution, you must include the language items you just created in a serialization module. Because the en item comes out-of-the-box with Sitecore, you can use rules to ignore it.

To configure serialization for language items:

  1. In src\Items.module.json, add an include for /sitecore/system/Languages:

    RequestResponse
      {
          "name": "languages",
          "path": "/sitecore/system/languages",
          "rules": [
              {
                  "path": "/en",
                  "scope": "ignored"
              }
          ]
      }
    
  2. To serialize the language items and your changes to the site content, run dotnet sitecore ser pull from the Sitecore CLI.

Do you have some feedback for us?

If you have suggestions for improving this article,