Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ bld/

# Visual Studio 2017 auto generated files
Generated\ Files/
.generated/

# MSTest test Results
[Tt]est[Rr]esult*/
Expand Down
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
<PackageVersion Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.12.19" />
<PackageVersion Include="Microsoft.VisualStudioEng.MicroBuild.Core" Version="1.0.0" />
<PackageVersion Include="Microsoft.TypeScript.MSBuild" Version="5.6.2" />
<PackageVersion Include="Microsoft.CodeAnalysis.ResxSourceGenerator" Version="3.11.0-beta1.24508.2" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)'=='netstandard2.0'">
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="$(RuntimeVersion9)" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
---
title: Localization
order: 0030
category: 10|Get Started
icon: Regular.Translate
route: /localization
---

# Localization

Localization allows the text in some components to be translated.

## Explanation

**FluentUI Blazor** itself provides English language strings for texts found in.
To customize translations in **FluentUI Blazor**, you can register a custom `IFluentLocalizer` implementation as a service.

Here's a step-by-step guide:

1. **Create a Custom Localizer**

Implement the `IFluentLocalizer` interface to provide your custom translations.

```csharp
using Microsoft.FluentUI.AspNetCore.Components;

public class CustomFluentLocalizer : IFluentLocalizer
{
public string this[string key, params object[] arguments]
{
get
{
// Provide custom translations based on the key
return key switch
{
"SomeKey" => "Your Custom Translation",
"AnotherKey" => String.Format("Another Custom Translation {0}",

// Fallback to the Default/English if no translation is found
_ => IFluentLocalizer.GetDefault(key, arguments)
};
}
}
}
```

> **Note:**
>
> The list of keys can be found in the `Core\Microsoft.FluentUI.AspNetCore.Components\Localization\LanguageResource.resx` file.

2. **Register the Custom Localizer**

Register your custom localizer in the `Program.cs` file, during the service registration.

```csharp
builder.Services.AddFluentUIComponents(config => config.Localizer = new CustomFluentLocalizer());
```

## Globalization and localization

For Blazor localization guidance, which adds to or supersedes the guidance in this article,
see [ASP.NET Core Blazor globalization and localization](https://learn.microsoft.com/aspnet/core/blazor/globalization-localization).

In summary, you need to:

1. Add localization services

Apps are localized using [Localization Middleware](https://learn.microsoft.com/aspnet/core/fundamentals/localization#localization-middleware).
Add localization services to the app with AddLocalization.

Add the following line to the `Program.cs` file, where services are registered:

```csharp
builder.Services.AddLocalization();
```

2. Dynamically set the culture from the `Accept-Language` header.

```csharp
app.UseRequestLocalization(new RequestLocalizationOptions()
.AddSupportedCultures(new[] { "en-US", "es-CR", "fr", "nl" })
.AddSupportedUICultures(new[] { "en-US", "es-CR", "fr", "nl" }));
```

## Example using an embedded resource (`.resx` file)

You can use an embedded resource to store your translations.

1. Create a resource file

Create a resource file with the translations. The file should be named `FluentLocalizer.resx` and should be placed in the `Resources` folder.
Verify that the `Build Action` property of the file is set to `Embedded Resource`,
and the `Custom Tool` property is set to `ResXFileCodeGenerator` (or `PublicResXFileCodeGenerator`).

2. Add other languages

Add other languages by creating a resource file with the same name as the default resource file, but with the language code appended.
For example, for French, create a file named `FluentLocalizer.fr.resx`.

3. Create a custom localizer

Add this code to read the translations from the resource file:
```csharp
public class EmbeddedCodeGeneratedLocalizer : IFluentLocalizer
{
/// <summary>
/// Gets the string resource with the given key, depending of the current UI culture.
/// </summary>
/// <param name="key"></param>
/// <param name="arguments"></param>
/// <returns></returns>
public string this[string key, params object[] arguments]
{
get
{
// Need to add
// - builder.Services.AddLocalization();
// - app.UseRequestLocalization(new RequestLocalizationOptions().AddSupportedUICultures(["en", "fr", "nl"]));

// Gets the localized version of the string
var localizedString = Resources.FluentLocalizer.ResourceManager.GetString(key, CultureInfo.CurrentCulture);

// Fallback to the Default/English if no translation is found
return localizedString == null
? IFluentLocalizer.GetDefault(key, arguments)
: string.Format(CultureInfo.CurrentCulture, localizedString, arguments);
}
}
}
```
41 changes: 40 additions & 1 deletion examples/Demo/FluentUI.Demo/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// MIT License - Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------------------

using System.Globalization;
using FluentUI.Demo.Client;
using Microsoft.FluentUI.AspNetCore.Components;

Expand All @@ -15,8 +16,14 @@

builder.Services.AddHttpClient();

// Add localization services
builder.Services.AddLocalization();

// Add FluentUI services
builder.Services.AddFluentUIComponents();
builder.Services.AddFluentUIComponents(config =>
{
config.Localizer = new MyLocalizer();
});

// Add Demo server services
builder.Services.AddFluentUIDemoServices().ForServer();
Expand All @@ -40,9 +47,41 @@

app.UseAntiforgery();

// Use the localization services
app.UseRequestLocalization(new RequestLocalizationOptions().AddSupportedUICultures(["en", "fr"]));

app.MapRazorComponents<FluentUI.Demo.Components.App>()
.AddInteractiveServerRenderMode()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(FluentUI.Demo.Client._Imports).Assembly);

app.Run();

internal class MyLocalizer : IFluentLocalizer
{
public string this[string key, params object[] arguments]
{
get
{
// Need to add
// - builder.Services.AddLocalization();
// - app.UseRequestLocalization(new RequestLocalizationOptions().AddSupportedUICultures(["fr"]));
var language = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;

Console.WriteLine(language);

// Returns the French version of the string
if (language == "fr")
{
return key switch
{
"FluentSample_Hello" => "Bonjour",
_ => IFluentLocalizer.GetDefault(key, arguments),
};
}

// By default, returns the English version of the string
return IFluentLocalizer.GetDefault(key, arguments);
}
}
}
4 changes: 4 additions & 0 deletions src/Core/Components/Base/FluentComponentBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ public abstract class FluentComponentBase : ComponentBase, IAsyncDisposable, IFl
[Inject]
private IJSRuntime JSRuntime { get; set; } = default!;

/// <summary />
[Inject]
protected IFluentLocalizer Localizer { get; set; } = FluentLocalizerInternal.Default;

/// <summary>
/// Gets the JavaScript module imported with the <see cref="FluentJSModule.ImportJavaScriptModuleAsync"/> method.
/// You need to call this method (in the `OnAfterRenderAsync` method) before using the module.
Expand Down
6 changes: 5 additions & 1 deletion src/Core/Components/Base/FluentInputBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ protected FluentInputBase()
[Inject]
private IJSRuntime JSRuntime { get; set; } = default!;

/// <summary />
[Inject]
protected IFluentLocalizer Localizer { get; set; } = FluentLocalizerInternal.Default;

/// <summary>
/// Gets the JavaScript module imported with the <see cref="FluentJSModule.ImportJavaScriptModuleAsync"/> method.
/// You need to call this method (in the `OnAfterRenderAsync` method) before using the module.
Expand Down Expand Up @@ -152,7 +156,7 @@ protected virtual async Task ChangeHandlerAsync(ChangeEventArgs e)
protected virtual string? GetAriaLabelWithRequired()
{
return (AriaLabel ?? Label ?? string.Empty) +
(Required ? $", Required" : string.Empty);
(Required ? $", {Localizer["FluentInputBase_Required"]}" : string.Empty);
}

#endregion
Expand Down
4 changes: 3 additions & 1 deletion src/Core/Components/Layout/FluentLayoutHamburger.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public partial class FluentLayoutHamburger
/// Gets or sets the title to display when the user hovers over the hamburger icon.
/// </summary>
[Parameter]
public string Title { get; set; } = "Menu";
public string? Title { get; set; }

/// <summary>
/// Gets or sets the icon to display.
Expand Down Expand Up @@ -73,6 +73,8 @@ public partial class FluentLayoutHamburger
/// <summary />
protected override void OnInitialized()
{
Title = Localizer["FluentLayoutHamburger_Title"];

var layout = Layout ?? LayoutContainer;
layout?.AddHamburger(this);
}
Expand Down
2 changes: 2 additions & 0 deletions src/Core/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ public static IServiceCollection AddFluentUIComponents(this IServiceCollection s
services.AddSingleton(options);
*/

services.AddScoped<IFluentLocalizer>(provider => configuration?.Localizer ?? FluentLocalizerInternal.Default);

return services;
}

Expand Down
5 changes: 5 additions & 0 deletions src/Core/Infrastructure/LibraryConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ public class LibraryConfiguration
/// </summary>
public bool UseTooltipServiceProvider { get; set; } = true;

/// <summary>
/// Gets or sets the FluentLocalizer instance used to localize the library components.
/// </summary>
public IFluentLocalizer? Localizer { get; set; }

/// <summary>
/// Gets or sets the value indicating whether the library should validate CSS class names.
/// respecting the following regex: "^-?[_a-zA-Z]+[_a-zA-Z0-9-]*$".
Expand Down
23 changes: 23 additions & 0 deletions src/Core/Localization/FluentLocalizerExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// ------------------------------------------------------------------------
// MIT License - Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------------------

namespace Microsoft.FluentUI.AspNetCore.Components;

/// <summary>
/// Extensions Localizer that uses the FluentUI language resource to localize strings.
/// </summary>
public static class FluentLocalizerExtensions
{
/// <summary>
/// Gets the default string resource (English) with the given name.
/// </summary>
/// <param name="localizer">The localizer.</param>
/// <param name="key">The name of the string resource.</param>
/// <param name="arguments">The list of arguments to be passed to the string resource.</param>
/// <returns>The string resource.</returns>
public static string GetDefault(this IFluentLocalizer localizer, string key, params object[] arguments)
{
return IFluentLocalizer.GetDefault(key, arguments);
}
}
31 changes: 31 additions & 0 deletions src/Core/Localization/FluentLocalizerInternal.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// ------------------------------------------------------------------------
// MIT License - Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------------------

namespace Microsoft.FluentUI.AspNetCore.Components;

/// <summary>
/// Localizer that uses the FluentUI language resource to localize strings.
/// </summary>
internal class FluentLocalizerInternal : IFluentLocalizer
{

/// <summary>
/// Gets the default IFluentLocalizer.
/// </summary>
public static readonly IFluentLocalizer Default = new FluentLocalizerInternal();

/// <summary>
/// Gets the string resource with the given name.
/// </summary>
/// <param name="key">The name of the string resource.</param>
/// <param name="arguments">The list of arguments to be passed to the string resource.</param>
/// <returns>The string resource.</returns>
public virtual string this[string key, params object[] arguments]
{
get
{
return IFluentLocalizer.GetDefault(key, arguments);
}
}
}
39 changes: 39 additions & 0 deletions src/Core/Localization/IFluentLocalizer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// ------------------------------------------------------------------------
// MIT License - Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------------------

namespace Microsoft.FluentUI.AspNetCore.Components;

/// <summary>
/// Localizer that uses the FluentUI language resource to localize strings.
/// </summary>
public interface IFluentLocalizer
{
/// <summary>
/// Gets the string resource with the given name.
/// </summary>
/// <param name="key">The name of the string resource.</param>
/// <param name="arguments">The list of arguments to be passed to the string resource.</param>
/// <returns>The string resource.</returns>
string this[string key, params object[] arguments] { get; }

/// <summary>
/// Gets the default string resource (English) with the given name.
/// </summary>
/// <param name="key">The name of the string resource.</param>
/// <param name="arguments">The list of arguments to be passed to the string resource.</param>
/// <returns>The string resource.</returns>
public static string GetDefault(string key, params object[] arguments)
{
var localizedString = Localization.LanguageResource.ResourceManager.GetString(key, System.Globalization.CultureInfo.InvariantCulture);

if (localizedString == null)
{
throw new ArgumentException($"Key '{key}' not found in LanguageResource.", paramName: nameof(key));
}

return arguments.Length > 0
? string.Format(System.Globalization.CultureInfo.InvariantCulture, localizedString, arguments)
: localizedString;
}
}
Loading