Deferred translation

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

  • Creating and using resource files.
  • Project preparation
  • Implementing the browser language strategy.
  • Implementing the local storage strategy.
  • Implementing the URL strategy.
You can download the example code used in this topic on GitHub.

Creating and using resource files

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:

centralized-resource.png

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:

distributed-resource.png

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.


Project preparation

  1. Install the Microsoft.Extensions.Localization NuGet library.
  2. To modify the csproj.cs file, right-click on your project and select Edit Project File. Then, add the following code to the file:

edit-csproj-file.png

<PropertyGroup>
    ...
    <BlazorWebAssemblyLoadAllGlobalizationData>
        true
    </BlazorWebAssemblyLoadAllGlobalizationData>
</PropertyGroup>
  1. In your component, inject 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.


Implementing the browser language strategy

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.

browser-language-example.png

  1. Add the code for a centralized resource or distributed resource to your Program.cs file.

Implementing the local storage strategy

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.

local-strorage-example.png

  1. Add the code for a centralized resource or distributed resource to your Program.cs file.
  2. In your index.html file, add the JavaScript code to change the local storage:
<script src="_framework/blazor.webassembly.js"></script>
<script>
    window.blazorCulture = {
        get: () => window.localStorage['BlazorCulture'],
        set: (value) => window.localStorage['BlazorCulture'] = value
    };
</script>
  1. Set the website language based on the value of the local storage in your Program.cs file:
// 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);
}
  1. Build the language selector component.
@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));
    }
}

Implementing the URL strategy

The URL strategy allows users to easily switch to their preferred language or share a link with the preferred language

url-example.png

  1. Add the code for a centralized resource or distributed resource to your Program.cs file.
  2. Set the website language based on the URL in your Program.cs file:
// 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);
}
BLAZOR SCHOOL
Designed and built with care by our dedicated team, with contributions from a supportive community. We strive to provide the best learning experience for our users.
Docs licensed CC-BY-SA-4.0
Copyright © 2021-2024 Blazor School
An unhandled error has occurred. Reload 🗙