Jan
Jan

Reputation: 5254

How can I translate strings in Blazor components and App.razor?

I want to localize strings of shared components like "NavMenu.razor" or the "App.razor" page.

I managed to translate content in my pages as described in the general .NET Core instruction and the more specific Blazor documentation:

This approach did not work for neither "NavMenu.razor" nor "App.razor".

Please note: I use MatNavMenu from the MatBlazor UI lib for main navigation.

I cannot find it documented anywhere. Help is much appreciated.

Upvotes: 2

Views: 5916

Answers (1)

Brian Parker
Brian Parker

Reputation: 14553

Easy:

  • Install Microsoft.Extensions.Localization

  • in programs.cs

    builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
    builder.Services.AddScoped<IStringLocalizer<App>,StringLocalizer<App>>();
    
  • Create a Resources folder in your client project. Add a resx file to that for instance App.resx this will be your default resources. Then add more files for each language you wish to support. App.fr.resx App.es.resx ect.

enter image description here

Then in a component inject

    @inject IStringLocalizer<App> L
    
    @L["YourText"]

The localizer will use browsers language and look in, in my case, App.en-AU.resx, App.en.resx, App.resx order for the key. If not found it will use "YourText"

Here is a blazor WASM project repo

Upvotes: 11

Related Questions