Skip to content

Instantly share code, notes, and snippets.

@nickwesselman
Created August 17, 2020 14:50
Show Gist options
  • Save nickwesselman/0f9e7ef62fff70c5d2befd69481e4008 to your computer and use it in GitHub Desktop.
Save nickwesselman/0f9e7ef62fff70c5d2befd69481e4008 to your computer and use it in GitHub Desktop.
Sitecore ASP.NET Core Language Switcher Snippets
@model LanguageSwitcherModel
@foreach (var culture in Model.SupportedCultures)
{
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>
}
}
using System.Collections.Generic;
using System.Globalization;
namespace DevExAcceptance.Models
{
public class LanguageSwitcherModel
{
public CultureInfo CurrentUICulture { get; set; }
public List<CultureInfo> SupportedCultures { get; set; }
public string CurrentSitecoreRoute { get; set; }
}
}
using DevExAcceptance.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DevExAcceptance.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);
}
}
}
// Need to configure localization options in ConfigureServices so we can access them later via DI
services.Configure<RequestLocalizationOptions>(options =>
{
// If you add languages in Sitecore which this site / Rendering Host should support, add them here.
var supportedCultures = new List<CultureInfo> { new CultureInfo(_defaultLanguage), new CultureInfo("en-GB") };
options.DefaultRequestCulture = new RequestCulture(_defaultLanguage, _defaultLanguage);
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
// Allow culture to be resolved via standard Sitecore URL prefix and query string (sc_lang).
options.UseSitecoreRequestLocalization();
});
//Then in Configure you can just call
app.UseRequestLocalization();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment