Walkthrough: Creating a language switcher component
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.
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:
-
Create and start an ASP.NET Core based solution as described in the Getting Started guide.
-
In Visual Studio, in the
rendering
project, open theStartup.cs
class.NoteSome changes are required in this class to make the ASP.NET Core
RequestLocalizationOptions
available to our language switcher through dependency injection. -
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(); });
-
In the
Configure
method, remove the existing call toapp.UseRequestLocalization
and replace it with a simpler one:RequestResponse// Enable ASP.NET Core localization, required for Sitecore content localization. app.UseRequestLocalization();
-
In the
Models
folder of therendering
project, add a new model class for the language switcher. This class outputs current and available languages. Add the following code in the class:RequestResponseusing 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; } } }
-
Create a new folder in the
rendering
project calledViewComponents
, 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:RequestResponseusing 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); } } }
-
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 calledDefault.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>
-
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
-
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>
-
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.
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:
-
Log in to the CM environment (
cm.myproject.localhost
) and open the Content Editor from the Launchpad. -
Under
/sitecore/system/languages
, add the languages you want, for example, German (Germany) and Japanese (Japan). This process creates language items forde-DE
andja-JP
. -
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: こんにちは
-
-
Publish the language additions and content changes.
-
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:
-
In
src\Items.module.json
, add an include for/sitecore/system/Languages
:RequestResponse{ "name": "languages", "path": "/sitecore/system/languages", "rules": [ { "path": "/en", "scope": "ignored" } ] }
-
To serialize the language items and your changes to the site content, run
dotnet sitecore ser pull
from the Sitecore CLI.