Localization
Localization is the process of customizing an application for a given language and region. BootstrapBlazor
A component allows you to translate its UI elements into the desired language. This includes text for buttons, filter operator properties, etc. The component uses the current request by default UI
Culture language, this article will show you how to use this feature in your app:
How localization works in components
BootstrapBlazor
Components additionally support the use of Json
Type key-value information as a resource file, which is parsed as UI
String rendered in。BootstrapBlazor The package comes with the following resource files。
- Chinese (zh)
- English (en)
json
localization file- German (de)
- Portuguese (pu)
- Spanish (es)
- 中國台灣 (zh-TW)
zh-CN
When the corresponding culture resource file is not provided, the built-in logic tries to localize through the parent culture to zh-CN
For example, the fallback mechanism is as follows:zh-CN
arrive zh
FallbackCulture
The cultural information set by the parameter is localized, the default is en
Centos
Ubuntu
mac
After the program runs, the thread cannot obtain the cultural information, and the default cultural information can be set through the configuration file:{
"BootstrapBlazorOptions": {
"DefaultCultureInfo": "en"
}
}
Enable localization
Server-Side App
1. configuration file
pass FallbackCultureName
Set the fallback culture information, that is, use this configuration culture when the currently requested culture information is not found, through SupportedCultures
Set supported cultures collection
{
"BootstrapBlazorOptions": {
"FallbackCultureName": "en",
"SupportedCultures": [
"zh-CN",
"en-US"
]
}
}
2. Enable .NET Core localization service
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
// Add Bootstrap Blazor components
builder.Services.AddBootstrapBlazor();
// Add multi-language support configuration information
builder.Services.AddRequestLocalization<IOptionsMonitor<BootstrapBlazorOptions>>((localizerOption, blazorOption)=>
{
blazorOption.OnChange(op => Invoke(op));
Invoke(blazorOption.CurrentValue);
void Invoke(BootstrapBlazorOptions option)
{
var supportedCultures = option.GetSupportedCultures();
localizerOption.SupportedCultures = supportedCultures;
localizerOption.SupportedUICultures = supportedCultures;
}
});
var app = builder.Build();
// Enable localization
var option = app.Services.GetService<IOptions<RequestLocalizationOptions>>();
if (option != null)
{
app.UseRequestLocalization(option.Value);
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Add BootstrapBlazor component
services.AddBootstrapBlazor();
// Add localization service configuration information
services.AddRequestLocalization<IOptions<BootstrapBlazorOptions>>((localizerOption, blazorOption) =>
{
var supportedCultures = blazorOption.Value.GetSupportedCultures();
localizerOption.SupportedCultures = supportedCultures;
localizerOption.SupportedUICultures = supportedCultures;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Enable localization middleware and set supported culture info
app.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>()!.Value);
}
}
3. Implement UI localization information storage (for example, cookies)
[Route("[controller]/[action]")]
public class CultureController : Controller
{
public IActionResult SetCulture(string culture, string redirectUri)
{
if (!string.IsNullOrEmpty(culture))
{
HttpContext.Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture, culture)));
}
return LocalRedirect(redirectUri);
}
public IActionResult ResetCulture(string redirectUri)
{
HttpContext.Response.Cookies.Delete(CookieRequestCultureProvider.DefaultCookieName);
return LocalRedirect(redirectUri);
}
}
3. Add UI that allows users to change localization
@inherits BootstrapComponentBase
@inject IOptions<BootstrapBlazorOptions> BootstrapOptions
@inject NavigationManager NavigationManager
@inject ICultureStorage CultureStorage
<div @attributes="@AdditionalAttributes" class="@ClassString">
<label>Please select language:</label>
<Select Value="@SelectedCulture" OnSelectedItemChanged="@SetCulture">
<Options>
@foreach (var kv in Configuration.GetSupportCultures())
{
<SelectOption Text="@kv.Key" Value="@kv.Value" />
}
</Options>
</Select>
</div>
@code {
private string? ClassString => CssBuilder.Default("culture-selector")
.AddClassFromAttributes(AdditionalAttributes)
.Build();
private string SelectedCulture { get; set; } = CultureInfo.CurrentUICulture.Name;
private async Task SetCulture(SelectedItem item)
{
if (CultureStorage.Mode == CultureStorageMode.Webapi)
{
// Using the api method is suitable for Server-Side mode
if (SelectedCulture != item.Value)
{
var culture = item.Value;
var uri = new Uri(NavigationManager.Uri).GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped);
var query = $"?culture={Uri.EscapeDataString(culture)}&redirectUri={Uri.EscapeDataString(uri)}";
// use a path that matches your culture redirect controller from the previous steps
NavigationManager.NavigateTo("/Culture/SetCulture" + query, forceLoad: true);
}
}
else
{
var cultureName = item.Value;
if (cultureName != CultureInfo.CurrentCulture.Name)
{
await JSRuntime.SetCulture(cultureName);
var culture = new CultureInfo(cultureName);
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;
NavigationManager.NavigateTo(NavigationManager.Uri, forceLoad: true);
}
}
}
}
4. additional Json
resource
BootstrapBlazor
The component library supports Microsoft's default resx
Format resource, also supports embedded json
format resources, and specific physical json
document
- Microsoft resx embedded resource file
- External json physical file
- json embedded resource file
- Built-in json resource file
public void ConfigureServices(IServiceCollection services)
{
services.AddBootstrapBlazor(null, options =>
{
// Ignore cultural info loss logs
options.IgnoreLocalizerMissing = true;
// Set up RESX format multilingual resource files such as Program.{CultureName}.resx
options.ResourceManagerStringLocalizerType = typeof(Program);
// Set Json format embedded resource file
options.AdditionalJsonAssemblies = new[] { typeof(BootstrapBlazor.Shared.App).Assembly };
// Set Json physical path file
options.AdditionalJsonFiles = new string[]
{
@"D:\Argo\src\BootstrapBlazor\src\BootstrapBlazor.Server\Locales\zh-TW.json",
@"D:\Argo\src\BootstrapBlazor\src\BootstrapBlazor.Server\Locales\zh-CN.json"
};
});
}
or use service extension method ConfigureJsonLocalizationOptions
public void ConfigureServices(IServiceCollection services)
{
services.AddBootstrapBlazor();
services.ConfigureJsonLocalizationOptions(options =>
{
// Ignore the loss of localized key-value culture information
options.IgnoreLocalizerMissing = true;
// Attach your own json multilingual culture resource file such as zh-TW.json
options.AdditionalJsonAssemblies = new Assembly[]
{
typeof(BootstrapBlazor.Shared.App).Assembly,
};
// Set Json physical path file
options.AdditionalJsonFiles = new string[]
{
@"D:\Argo\src\BootstrapBlazor\src\BootstrapBlazor.Server\Locales\zh-TW.json",
@"D:\Argo\src\BootstrapBlazor\src\BootstrapBlazor.Server\Locales\zh-CN.json"
};
});
}
Web Assembly
1. Enable .NET Core localization service
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
// Add BootstrapBlazor component
builder.Services.AddBootstrapBlazor();
builder.Services.AddSingleton<ICultureStorage, DefaultCultureStorage>();
// increase localization
builder.Services.Configure<BootstrapBlazorOptions>(op =>
{
op.ToastDelay = 4000;
op.SupportedCultures = new List<string> { "zh-CN", "en-US" };
});
var host = builder.Build();
await GetCultureAsync(host);
await host.RunAsync();
}
private static async Task GetCultureAsync(WebAssemblyHost host)
{
var jsRuntime = host.Services.GetRequiredService<IJSRuntime>();
var cultureName = await jsRuntime.GetCulture() ?? "zh-CN";
var culture = new CultureInfo(cultureName);
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
}
internal class DefaultCultureStorage : ICultureStorage
{
public CultureStorageMode Mode { get; set; } = CultureStorageMode.LocalStorage;
}
2. Implement UI localization information storage (for example, localStorage)
Consistent with Server-Side
Change the default language setting
public static async Task Main(string[] args)
{
// Set default culture to zh-CN
CultureInfo.CurrentCulture = new CultureInfo("zh-CN");
CultureInfo.CurrentUICulture = new CultureInfo("zh-CN");
// ...
var host = builder.Build();
await GetCultureAsync(host);
await host.RunAsync();
}
Configure whether to display missing localized resource information
"BootstrapBlazorOptions": {
"IgnoreLocalizerMissing": true
}
var builder = WebApplication.CreateBuilder(args);
// Add BootstrapBlazor service
builder.Services.AddBootstrapBlazor(null, options =>
{
// Ignore the loss of localized key-value culture information
options.IgnoreLocalizerMissing = true;
});
B station related video link