🟥 Not applicable to Blazor Server
One of the biggest challenges of building multilingual websites is managing translations efficiently. Blazor provides a powerful feature called deferred translation, which enables the seamless translation of text in your web application. With deferred translation, when a user changes the language preference, the website remembers it for future visits, but the language selection may not take effect until the user refreshes the website. In this tutorial, we will cover:
You can download the example code used in this topic on GitHub.
Deferred translation in Blazor only accepts RESX files as resources by default. By default, the RESX files must be located with the component (centralized resource), as shown in the following image:
However, centralizing resources can pose challenges when it comes to maintenance. To address this, you can distribute resource files into a separate folder from your component and reconstruct the component folder tree inside a folder, as shown in the following image:
If you have centralized your resource files, you can add the following code to your Program.cs file:
builder.Services.AddLocalization();
On the other hand, if you have distributed your resource files, you can add the following code to your Program.cs file:
builder.Services.AddLocalization(options => options.ResourcesPath = "BlazorSchoolResources");
In this case, BlazorSchoolResources
is the root resource folder where your resource files are located.
Microsoft.Extensions.Localization
NuGet library.<PropertyGroup> ... <BlazorWebAssemblyLoadAllGlobalizationData> true </BlazorWebAssemblyLoadAllGlobalizationData> </PropertyGroup>
IStringLocalizer<T>
, where T
represents your component type and uses IStringLocalizer<T>
to display text in multiple languages. For example, in ChangeLanguageDemonstrate.razor:@inject IStringLocalizer<ChangeLanguageDemonstrate> Localizer @Localizer["String1"]
In the example above, String1
is your resource key.
You can also pass parameters to the localizer. To do this, add a placeholder in the translated text, such as "Hello {0}, {1}"
. Then, use @Localizer["Hello {0}, {1}", "Blazor School", "Blazor School Books"]
to replace the placeholder with parameters.
The browser language strategy is one of the methods that can be used to determine a user's preferred language in a multilingual website.
When a user visits a website, their browser sends a request header that contains information about the user's preferred language(s). This information is based on the language settings that the user has configured in their browser.
The browser language strategy works by checking the value of the Accept-Language
header in the incoming request, and then using that information to select the appropriate language for the website. If the website supports the user's preferred language, it will display content in that language. If the preferred language is not supported, the website may fall back to a default language or display an error message.
The local storage strategy is a language selection method used by developers to determine a user's preferred language when creating a multilingual website. Local storage is a web storage API that allows web applications to store data locally within a user's browser.
With the local storage strategy, developers can store the user's preferred language as a value in the local storage object. When the user visits the website again, the website can read the stored value from the local storage object and display the website content in the preferred language.
<script src="_framework/blazor.webassembly.js"></script> <script> window.blazorCulture = { get: () => window.localStorage['BlazorCulture'], set: (value) => window.localStorage['BlazorCulture'] = value }; </script>
// await builder.Build().RunAsync(); var host = builder.Build(); await SetWebsiteLanguageAsync(host); await host.RunAsync(); static async Task SetWebsiteLanguageAsync(WebAssemblyHost host) { var js = host.Services.GetRequiredService<IJSRuntime>(); string userPreferenceLanguage = await js.InvokeAsync<string>("blazorCulture.get"); string chosenLanguage = string.IsNullOrEmpty(userPreferenceLanguage) ? "en" : userPreferenceLanguage; CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(chosenLanguage); CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(chosenLanguage); }
@inject IJSRuntime JSRuntime <select @onchange="OnChangeLanguage"> <option value="">Select</option> <option value="en">English</option> <option value="fr">France</option> </select> @code { private void OnChangeLanguage(ChangeEventArgs e) { string selectedLanguage = e.Value?.ToString() ?? "en"; InvokeAsync(() => JSRuntime.InvokeVoidAsync("blazorCulture.set", selectedLanguage)); } }
The URL strategy allows users to easily switch to their preferred language or share a link with the preferred language
// await builder.Build().RunAsync(); var host = builder.Build(); SetWebsiteLanguage(host); await host.RunAsync(); static void SetWebsiteLanguage(WebAssemblyHost host) { var navigationManager = host.Services.GetRequiredService<NavigationManager>(); var uri = new Uri(navigationManager.Uri); var urlParameters = HttpUtility.ParseQueryString(uri.Query); var defaultCulture = CultureInfo.GetCultureInfo("fr"); string urlQueryKey = "language"; CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(urlParameters[urlQueryKey] ?? defaultCulture.Name); CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(urlParameters[urlQueryKey] ?? defaultCulture.Name); }