Skip to content

Localization ​

Introduction ​

DotBlaze's localization is Laravel's: translation strings live in the lang directory, and __("...") (or Lang.Get) returns the text in the current locale.

html
<h1>@__("Welcome to :app", new { app = Config.Get<string>("app.name") })</h1>

Configuring the Locale ​

In config/App.cs:

csharp
locale = "en",
fallback_locale = "en",

A string missing in the current locale is taken from the fallback locale, and failing that the key itself is shown. The lang directory can be moved with app.lang_path.

Defining Translation Strings ​

Using Translation Strings as Keys ​

For an application with many strings, write them in the default language in your views, and translate them in one JSON file per locale. From the sample app's lang/id.json:

json
{
  "Posts": "Tulisan",
  "Welcome to :app": "Selamat datang di :app",
  "Deleting your account also deletes your :count posts.": "Menghapus akun juga menghapus :count tulisan Anda."
}

Using Short Keys ​

Files in a folder per locale hold short keys, used as file.key. Nested objects are joined with dots:

json
// lang/en/messages.json
{
  "welcome": "Welcome, :name",
  "errors": { "not_found": "Nothing here." }
}
csharp
Lang.Get("messages.welcome", new { name = "Ali" });   // "Welcome, Ali"
Lang.Get("messages.errors.not_found");

The JSON files may contain comments and trailing commas. They are read once, the first time a locale is used. The template's project file copies lang/**/*.json to the build output.

Retrieving Translation Strings ​

__ is a global function in DotBlaze applications (from DotBlaze.Support.Functions), in C# and in Razor views:

csharp
var text = __("Welcome back!");
var other = Lang.Get("messages.welcome", new { name }, locale: "id");   // a specific locale
if (Lang.Has("messages.welcome")) { ... }                              // without the fallback

Replacing Parameters ​

Placeholders start with a colon. Like Laravel, the capitalization of the placeholder decides the capitalization of the value:

csharp
// "welcome": "Welcome, :name"   → Welcome, ali
// "welcome": "Welcome, :Name"   → Welcome, Ali
// "welcome": "Welcome, :NAME"   → Welcome, ALI
__("messages.welcome", new { name = "ali" });

Pluralization ​

Separate the singular and plural forms with |, or give explicit counts and ranges:

json
{
  "apples": "There is one apple|There are many apples",
  "basket": "{0} The basket is empty|{1} One apple|[2,9] A few apples|[10,*] :count apples"
}
csharp
Lang.Choice("messages.basket", 12);            // "12 apples" (:count is filled in)
TransChoice("messages.apples", 1);             // the global function: "There is one apple"

Changing the Locale per Request ​

Each request starts in app.locale. Lang.SetLocale changes it for the rest of the request; it also sets the .NET culture, so dates, numbers, and validation messages follow it. The sample app keeps the visitor's choice in the session with a middleware in the web group:

csharp
public sealed class SetLocale : IRouteMiddleware
{
    static readonly string[] Supported = ["en", "id"];

    public async Task Handle(HttpContext context, Func<Task> next)
    {
        if (context.Request.Query["lang"].ToString() is { Length: > 0 } wanted && Supported.Contains(wanted))
            await Session.Put("locale", wanted);
        if (await Session.Get<string>("locale") is { } locale) Lang.SetLocale(locale);
        await next();
    }
}

// AppServiceProvider.Boot
Route.AliasMiddleware<SetLocale>("locale");
Route.PushMiddlewareToGroup("web", "locale");

Lang.Locale is the current locale, and Lang.IsLocale("id") checks it, for example in the layout's <html lang="@Lang.Locale">. Because the middleware is in the page's route, live components on the page use the same locale for their updates. Queued jobs and notifications run in the locale they were dispatched in.

Validation Messages ​

Validation uses FluentValidation, which ships its messages in many languages and picks them by the current culture. After Lang.SetLocale("id"), a required field reads 'Email' tidak boleh kosong. without any translation file. Messages you write yourself with .WithMessage(...) can use __:

csharp
// Inside PostRequest : FormRequest<PostRequest>; import FluentValidation.
public override void Rules(RuleSet<PostRequest> rules)
{
    rules.Field(x => x.Title).NotEmpty()
        .WithMessage(_ => __("Give your post a title."));
}

Package Translations ​

A package registers its translations under a namespace. You then use them with :: in front of the key:

csharp
Lang.Get("courier::messages.welcome", new { name = "Ada" });

To change a package's wording, put your own lines in lang/vendor/courier, using the same layout as lang, for example lang/vendor/courier/id/messages.json. Your lines take precedence over the package's lines, and any line you leave out still comes from the package.

Complete Example: English and Indonesian ​

Create these files in the Blog template. Comments are supported by the translation loader:

json
// lang/en/docs.json
{
  "welcome": "Welcome, :name"
}
json
// lang/id/docs.json
{
  "welcome": "Selamat datang, :name"
}
csharp
// app/Commands/TranslationDemo.cs
using DotBlaze;

namespace Blog.Commands;

public class TranslationDemo : Command
{
    public override string Signature => "demo:translation";
    public override Task<int> Handle()
    {
        var english = Lang.Get("docs.welcome", new { name = "Ada" }, locale: "en");
        var indonesian = Lang.Get("docs.welcome", new { name = "Ada" }, locale: "id");
        if (english != "Welcome, Ada" || indonesian != "Selamat datang, Ada")
            throw new InvalidOperationException("Translation files were not loaded.");
        Line(english);
        Line(indonesian);
        return Task.FromResult(0);
    }
}

Run dotblaze demo:translation. Expected output is the two checked strings. The template copies lang/**/*.json into build output. Restart after changing translations already loaded by a process. For browser-selected language, use the middleware above and register it in the existing provider; never accept unsupported locale names without checking your supported list.