How to localize texts in your client-side Blazor WebAssembly App?
Tags: blazor, i18n, localization
Published: 2019-04-02 13:36:06

---
title: How to localize texts in your client-side Blazor WebAssembly App?
published: true
description: This article describe about How to localize texts in your Blazor App.
tags: Blazor,i18n,localization
---

# Introduction: What's "Blazor" (client-side)?

"Blazor" (client-side) is a Single Page Web Application (a.k.a "SPA") framework.

Client-side Blazor allows you to run C# code and .NET Standard 2.0 native assembly (.dll) on a top of modern web browser's WebAssembly engine, without any .NET server processes.

If you are new to Blazor, I recommend watching this YouTube video.

[NDC Oslo 2017 - "Web Apps can’t really do *that*, can they? - Steve Sanderson"](https://www.youtube.com/watch?v=MiLAE6HMr10&feature=youtu.be&t=31m59s)

The video was about prototype of Blazor, and the current version when I wrote this post was v.0.9.0, which had some breaking changes. But that video is useful to understanding the concept and pros/cons of "Blazor".


# Localization of client-side Blazor WebAssembly App

## Scope of this article

This article will only discuss text localization scenarios.

Date, time, and currency formats are outside the scope of this article.

~~And also, server-side Blazor is out of this article, too.~~
_[2019/11/09]  ["Blazor I18n Text" Library ver.7](https://www.nuget.org/packages/Toolbelt.Blazor.I18nText/) started support Server-Side Blazor! 🎉_

## Are there already any solutions for text localization?

Yes, we can find great solutions and articles about it on the internet.

For example:

- **"Localization In Blazor App Using Microsoft.JSInterop"**
    - https://www.c-sharpcorner.com/article/localization-in-blazor-app-using-microsoft-jsinterop/
- **"Internationalizing a Blazor App with ASPNET Core as backend service"**
    - https://remibou.github.io/I18n-with-Blazor-and-ASPNET-Core/

However, I couldn't be satisfied with the above solutions, because those solutions have consideration points below.

# The 4 reasons why I wasn't satisfied with the above solutions

## 1. It requires Server-Side implementation.

Blazor is a client-side solution, therefore, a Blazor app can deploy on static contents only HTTP server, like GitHub pages.

However, the above localization solutions require a server side ASP.NET Core implementation, and of course it requires Web server which can run ASP.NET Core.


## 2. It requires .resx editor.

.resx file is a just an XML format file, and it is popular to be used in localization scenario in general C# programming. 

However, to edit .resx file, you will need Visual Studio. It's hard work that editing .resx file with a text editor, I think.


## 3. It requires key access by "string".

A common text localization solution works as getting localized text from a "key".

In the above solutions, you must describe key by string in C#/Razor source code.

Writing a key as string often can be causing miss typing, and that miss can't detect at compile time.  
It also can't get the help of the code completion feature of an editor. (ex. "IntelliSense")

I really want to get static typing solutions rather than late binding solutions such as key accessing by string

## 4. It doesn't consider Blazor components libraries.

Blazor support creating and reusing component library as NuGet package.

However, the above solutions couldn't resolve the localization texts in Blazor component library package.

# I decided to make a new solution.

As mentioned above, I couldn't be satisfied any solutions which I found on the internet, therefore, I decided to make a new solution. 

## My approach is...

The most important point of my approach is, not only writing library code but **writing build script** for processing some tasks (such as generate static typing files, generate  localized text files as static contents) at build time.

- Use the simple JSON/CSV format instead of the .resx file format to writing the key-localized text corresponds table (I call it "localized text source file").
- Generate static typed C# class (I call it as "text table class") source code files from "localized text source files" on build automatically.
    - "text table class" has fields associated with each key in "localized test source file".
- And also generate JSON format files (I call it as "localized text resource JSON file") in under the "wwwroot" content folder from "localized text source files" on build automatically.
    - "localized text resource JSON files" are  deployed as static content files on a Web server, and those are fetched from Blazor client process at run time.  
- Include an "msbuild" script that makes "localized text resource JSON files" to be contained in a NuGet package of Blazor component library.

# ... and, I did it!

The result of my work is here:

- **Blazor Internationalization(I18n) Text** - "Toolbelt.Blazor.I18nText" NuGet package
    - [https://www.nuget.org/packages/Toolbelt.Blazor.I18nText/](https://www.nuget.org/packages/Toolbelt.Blazor.I18nText/)

## No .resx, simple JSON format, and also CSV format is available!

![fig](https://raw.githubusercontent.com/jsakamoto/Toolbelt.Blazor.I18nText/master/.assets/fig.001.png)

## It works on GitHub pages. (static contents only HTTP server)

- https://jsakamoto.github.io/Toolbelt.Blazor.I18nText/

![movie.1](https://raw.githubusercontent.com/jsakamoto/Toolbelt.Blazor.I18nText/master/.assets/movie-001.gif)

## IntelliSense works well.

![movie.2](https://raw.githubusercontent.com/jsakamoto/Toolbelt.Blazor.I18nText/master/.assets/movie-002.gif)

# How to use it?


### Step.1 - Add "Toolbelt.Blazor.I18nText" Package

Add `Toolbelt.Blazor.I18nText` NuGet package to your Blazor app project.

If you are using dotnet CLI, you can do it by command line bellow.

```
$ dotnet add package Toolbelt.Blazor.I18nText
```

You can also do it in Package Manager Console of Visual Studio, if you are using Visual Studio in Windows OS.

```
PM> Install-Package Toolbelt.Blazor.I18nText
```

### Step.2 - Create localized text source files as JSON or CSV

Add localized text source files for each language in a `i18ntext` folder under  your Blazor app project folder.

The localized text source files must be simple key-value only JSON file like a bellow example,

```json
{
  "Key1": "Localized text 1",
  "Key2": "Localized text 2",
  ...
}
```

or, 2 column only CSV file without header row like a bellow example.

```
Key1,Localized text 1
Key2,Localized text 2
```

**NOTICE** - The encoding of CSV file must be **UTF-8**.


And, the naming rule of localized text source files must be bellow.

```
<Text Table Name>.<Language Code>.{json|csv}
```

![fig.1](https://raw.githubusercontent.com/jsakamoto/Toolbelt.Blazor.I18nText/master/.assets/fig.001.png)

### Step.3 - Build the project always when localized text source files are created or updated.

After creating or updating those localized text source files, **you have to build your Blazor app project.**

After building the project, **"Typed Text Table class" C# files** will be generated in the `i18ntext/@types` folder, by the building process.

And also, **"Localized Text Resource JSON" files** will be generated at the `wwwroot/content/i18ntext` folder, too.

![fig.2](https://raw.githubusercontent.com/jsakamoto/Toolbelt.Blazor.I18nText/master/.assets/fig.002.png)

**NOTE** - If you want to do this automatically  whenever those localized text source files (.json or .csv) are changed, you can use `dotnet watch` command with following arguments.

```shell
$ dotnet watch msbuild -t:CompileI18nText
```

After entry this dotnet CLI command, the dotnet CLI process keep running and watch the changing of localized text source files.
When the dotnet CLI which keep running detect the changing of localized text source files, the dotnet CLI re-compile localized text source files into **"Typed Text Table class"** files and **"Localized Text Resource JSON" files**.

![fig.2-2](https://raw.githubusercontent.com/jsakamoto/Toolbelt.Blazor.I18nText/master/.assets/fig.002-2.png)

### Step.4 - Configure your app to use I18nText service

Open the C# source file of the "Startup" class of your Blazor app in your editor, and add `using` clause for opening `Toolbelt.Blazor.Extensions.DependencyInjection` namespace, and add following code in `ConfigureServices()` method of the startup class.

```csharp
services.AddI18nText<Startup>();
```

![fig.3](https://raw.githubusercontent.com/jsakamoto/Toolbelt.Blazor.I18nText/master/.assets/fig.003.png)

### Step.5 - Get the "Text Table" object in your Blazor component

Open your Blazor component file (.cshtml) in your editor, and do this:

1. Inject `Toolbelt.Blazor.I18nText.I18nText` service into the component.

```csharp
@inject Toolbelt.Blazor.I18nText.I18nText I18nText
```

2. Add a filed of the Text Table class generated from localized text source files, and assign the default instance.

```csharp
@functions {

    I18nText.MyText MyText = new I18nText.MyText();
```

**NOTE** - The namespace of the Text Table class is `<default namespace of your Blazor project>` + `"I18nText"`.

3. Override `OnInitAsync()` method of the Blazor component, and assign a Text Table object that's a return value of `GetTextTableAsync<T>()` method of `I18nText` service instance to the Text Table field.

```csharp
protected override async Task OnInitAsync()
{
  MyText = await I18nText.GetTextTableAsync<I18nText.MyText>(this);
```

![fig.4](https://raw.githubusercontent.com/jsakamoto/Toolbelt.Blazor.I18nText/master/.assets/fig.004.png)

### Step.6 - Use the Text Table

After doing the these steps, you can reference a field of the Text Table object to get localized text.

If you are using Visual Studio in Windows OS and Blazor extensions is installed in that Visual Studio, you can get "IntelliSense" and "Document comment" support.

![movie.2](https://raw.githubusercontent.com/jsakamoto/Toolbelt.Blazor.I18nText/master/.assets/movie-002.gif)

**_Note:_** Text Table object allows you to get localized text by key string dynamically, with indexer syntax, like this.

```html
<h1>@MyText["HelloWorld"]</h1>
```

This way is sometimes called "late binding".

This feature is very useful in some cases.  
However, if you make some mistakes that typo of key string, these mistakes will not be found at compile time. 
In this case, it will just return the key string as is without any runtime exceptions.

### Step.7 - Run it!

Build and run your Blazor app.

The I18nText service detects the language settings of the Web browser, and reads the localized text resource JSON which is most suitable for the language detected.

![fig.5](https://raw.githubusercontent.com/jsakamoto/Toolbelt.Blazor.I18nText/master/.assets/fig.005.png)

# Learn more

You can find more detail of this my work on GitHub.

- [https://github.com/jsakamoto/Toolbelt.Blazor.I18nText](https://github.com/jsakamoto/Toolbelt.Blazor.I18nText)

----

Happy coding with Blazor :)