---
title: "Walkthrough: Creating a language switcher component"
slug: "walkthrough--creating-a-language-switcher-component"
abstract: "How to create a language switcher component in a rendering host so users can select the language to display."
---
# Walkthrough: Creating a language switcher component

> [!important]
> If you integrated your ASP.NET Core app before September 2024, it's using the legacy ASP.NET Core Rendering SDK, version 22 or earlier. This SDK is no longer receiving updates, so we recommend that you [upgrade to the latest version of the new ASP.NET Core SDK](https://doc.sitecore.com/xmc/en/developers/asp-net/latest/asp-net-core-sdk/upgrade-from-v22.html).

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](https://doc.sitecore.com/xp/en/developers/hd/23/sitecore-headless-development/asp-net-core-rendering-engine.html "ASP.NET Core Rendering Engine").

This walkthrough describes how to:

- [Create the View component](https://doc.sitecore.com/xp/en/developers/hd/23/sitecore-headless-development/walkthrough--creating-a-language-switcher-component.html#UUID-ab4b7972-a91a-5db2-9db6-4e476889fa02_section-idm231968831467268 "Create the View component")
- [Add Sitecore languages and content](https://doc.sitecore.com/xp/en/developers/hd/23/sitecore-headless-development/walkthrough--creating-a-language-switcher-component.html#UUID-ab4b7972-a91a-5db2-9db6-4e476889fa02_section-idm231968838306676 "Add Sitecore languages and content")
- [Configure serialization for language items (optional)](https://doc.sitecore.com/xp/en/developers/hd/23/sitecore-headless-development/walkthrough--creating-a-language-switcher-component.html#UUID-ab4b7972-a91a-5db2-9db6-4e476889fa02_N1598442734135 "Configure serialization for language items (optional)")

<details>
<summary><h2>Create the View component</h2></summary>

This example uses an [ASP.NET Core view component](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-3.1) 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](https://doc.sitecore.com/xp/en/developers/hd/23/sitecore-headless-development/walkthrough--using-the-getting-started-template.html "Walkthrough: Using the Getting Started template").
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:

    ```csharp
    // 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:

    ```

    // 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:

    ```csharp
    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:

    ```csharp
    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:

    ```csharp
    @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](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-3.1):

    ```text
    @addTagHelper *, MyProject
    ```

9. Add the language switcher to `Views/Default/Index.cshtml` (the default View) under the Sitecore logo:

    ```xml
    <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`.

</details>

<details>
<summary><h2>Add Sitecore languages and content</h2></summary>

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.

</details>

<details>
<summary><h2>Configure serialization for language items (optional)</h2></summary>

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`:

    ```csharp
    {
          "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](https://doc.sitecore.com/xp/en/developers/104/developer-tools/sitecore-command-line-interface.html).

</details>