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)
Additional json localization file
  • German (de)
  • Portuguese (pu)
  • Spanish (es)
  • 中國台灣 (zh-TW)
The component has a built-in localization language fallback mechanism. For example, the request culture is 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
If the set localization language does not provide the resource file after falling back and still cannot find the resource file, use FallbackCulture The cultural information set by the parameter is localized, the default is en
pay attention:
Due to some systems such as 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

The resource file is a merge relationship, and the addressing rule priority is
  • 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

img
Themes
Bootstrap
Motronic
Ant Design (完善中)
DevUI (制作中)
LayUI (完善中)
An error has occurred. This application may no longer respond until reloaded. Reload
Seems like the connection with the server has been lost. It can be due to poor or broken network. Please hang on while we're trying to reconnect...
Oh snap! Failed to reconnect with the server. This is typically caused by a longer network outage, or if the server has been taken down. You can try to reconnect, but if that does not work, you need to reload the page.
Oh man! The server rejected the attempt to reconnect. The only option now is to reload the page, but be prepared that it won't work, since this is typically caused by a failure on the server.
Bootstrap Blazor Component library updated to 7.0.8-beta05

Bootstrap Blazor at present has more than 120 components. This component is based on Bootstrap Blazor An enterprise-level component library that provides several types of common components such as layout, navigation, form, data, notification, icon, voice, etc. Each component has been carefully designed with modularity, responsiveness and excellent performance. Starting from more practical scenarios, meeting the needs of various scenarios, greatly reducing the time cost of developers, greatly shortening the development cycle, greatly improving development efficiency, and providing a set of General Rights Management System Example project。Bootstrap Blazor Products are maintained by a professional full-time technical team, with efficient response speed, diversified solutions, long-term support, and enterprise-level support. At present, it has been used in many well-known state-owned enterprises, and the project is running stably with a maximum of 1200 people online. On the right is the QR code of the Chinese Blazor QQ community with the largest number of people in China, welcome to scan and join the group.

component updated to 6.6.0 Change log [portal] If the component brings you convenience, please help to light up the project Star github gitee

QQGroup
QQ 795206915