Giter Site home page Giter Site logo

darklikally / i18next.net Goto Github PK

View Code? Open in Web Editor NEW
54.0 5.0 29.0 724 KB

A port of the i18next javascript library for .Net platforms based on .Net Standard 2.0

License: Apache License 2.0

C# 100.00%
i18n i18next dotnet dotnet-core dotnet-standard csharp translation internationalization localization

i18next.net's Introduction

I18Next.Net

I18Next.Net is a port of I18Next for JavaScript. It implements most of the features provided by the original library and enhances this by some more .Net specific features.

Installation

Nuget:

Install-Package I18Next.Net

.NET Cli:

dotnet add package I18Next.Net

See Nuget for more information.

If you want to integrate with IServiceCollection also install I18Next.Net.Extensions

Install-Package I18Next.Net.Extensions

For further integration with AspNetCore you are also required to add the I18Next.Net.AspNetCore package.

Install-Package I18Next.Net.AspNetCore

See the usage information below for further help.

Basic Usage

Just for now, a quick description on how to use the library in an AspNetCore MVC application.

First you have to register the required services in your application startup. If you call the IntegrateToAspNetCore method you can use the default configuration for AspNetCore applications which includes an HTML-escaping interpolator and the language detection based on the requests Accept-Language header (internally it is based on the current thread language). I'll explain further below how to make the language detection work.

services.AddI18NextLocalization(i18n => i18n.IntegrateToAspNetCore());

Now you're ready to go using I18Next by simply injecting IStringLocalizer into your controllers and services.

// ...

private readonly IStringLocalizer<HomeController> _localizer;

public HomeController(IStringLocalizer<HomeController> localizer)
{
    _localizer = localizer;
}

public IActionResult About()
{
    ViewData["Message"] = _localizer["about.description"];

    return View();
}

// ...

If you also want to use view localization in your mvc application you should configure I18Next view localization by adding the following to your MVC builder.

services.AddMvc()
    .AddI18NextViewLocalization();

In order to make the language detection work let the app use request localization. Don't forget to specify the supported languages.

app.UseRequestLocalization(options => options.AddSupportedCultures("de", "en"));

You can always take a look at the Example.WebApp in the examples directory until there is a proper documentation about all the provided functionality.

To customize the locale file locations or use other backends just take a look at the i18next builder possibilities provided by the service registration.

services.AddI18NextLocalization(i18n => i18n
    .IntegrateToAspNetCore()
    .AddBackend(new JsonFileBackend("wwwroot/locales"))
    .UseDefaultLanguage("es"));

There are lots of more configuration options. More documentation will follow in the future.

Todo

  • Auto build pipeline
  • Further documentation
  • More tests
  • More examples
  • Configurable auto namespace/scope selection for IStringLocalizer<T>

i18next.net's People

Contributors

darklikally avatar maxwellwr avatar msjogren avatar p0k0 avatar shaddix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

i18next.net's Issues

Ready for production?

Hi, sorry for the weird issue. I am trying to decide on i18n solution for a rather big project we're working on. We are already using i18next on the frontend which would make this perfect in terms of compatibility of tools and the build process.

I, however, see that this lib is not widely adopted, and in order to save precious time, I was curious if you could help me understand the state of its development. Is this actively developed/maintained? Are there any issues that you currently are aware of that need fixing and/or is it ready for production? Did you do any performance testing comparing it to the more traditional dot net i18n frameworks?

Thank you very much for any kind of feedback you could provide here.

Split up language files

I was wondering how and if i can split up language files. For an example i would like to have the following folder structure:
locales/Controllers/Home/en.json
locales/Models/Home/en.json
locales/Services/Home/en.json

Is that possible? The default localisation .net Core offers, tries to guess where the localisations files are based on the path of the actual cs file. Unfortunately i am unable to figure out how it works with this library.

TranslationTree.GetAllValues() doesn't include parent key paths

Hello, I think i've found a bug or an oversight but i'm not sure.

Given this JSON translation file...

{
    "key": "value of key",
    "look": {
        "deep": "value of look deep"
    }
}

TranslationTree.GetAllValues() will return...

{
    "key": "value of key",
    "deep": "value of look deep"
}

I think the mistake is here: https://github.dev/DarkLiKally/I18Next.Net/blob/6dbd30f23a8655134dc7d2041fe803240584a3ad/src/I18Next.Net/TranslationTrees/TranslationTree.cs#L69-L70

The parent translation name (key path) isn't propagated through the recursion for use in the dictionary.

I think it's supposed to result in this dictionary instead

{
    "key": "value of key",
    "look.deep": "value of look deep"
}

Allow customization on localization files findings

Hi,
I would like to have my localization files structured like this:

  • locales/localization_en.json
  • locales/localization_de.json

The default JsonFileBackend has a method FindFile which is private. If this method (or even other methods) are defined protected virtual then the only effort is to implement the methods that are necessary. And re-use the code from the JsonFileBackend. One more additional benefit is that if you make changes to this class in future release, my custom class will inherit these changes automatically when I upgrade the I18Next NuGet package.
Please let me know what you think. Thank you

NullReferenceException when using ThreadLanguageDetector and Accept-Language header is not present

We receive the following exception:

System.ArgumentNullException: Value cannot be null.
  at I18Next.Net.I18NextNet.set_Language(String value)
  at I18Next.Net.Extensions.I18NextStringLocalizer.Translate(String name, Object[] arguments)

when Accept-Language header is not present in http request (e.g. from Mobile app, not web-browser).

Set up is:

services.AddI18NextLocalization(
                i18N => i18N
                    .AddLanguageDetector<ThreadLanguageDetector>()
);

Pluralization and fallback languages

Pluralization currently seems broken when used in combination with fallback languages. Different languages have different pluralization suffixes but DefaultTranslator.ResolveTranslationAsync right now only calls IPluralResolver for the main language and then reuses the possibleKeys for fallback languages.
Here's a failing test that can be added to I18NextFixture as an example.

`

    // Add this line to SetupBackend()
    backend.AddTranslation("en", "translation", "exampleKey2_plural", "My English plural fallback {{count}}.");

    [Test]
    public void Pluralization_MissingLanguage_ReturnsFallback()
    {
        _i18Next.Language = "ja";
        _i18Next.SetFallbackLanguages("en");
        Assert.AreEqual("My English plural fallback 2.", _i18Next.T("exampleKey2", new { count = 2 }));
    }

`

The original fallback language support PR #6 had this right but later refactoring broke it.
I'll submit a new PR that I believe fixes the problem.

CurrentCulture vs CurrentUICulture

According to the documentation of CurrentCulture & CurrentUICulture
https://docs.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo.currentculture?view=net-5.0
https://docs.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo.currentuiculture?view=net-5.0

the first one (CurrentCulture) defines the format of numbers and dates.
The second one (CurrentUICulture) defines which resource to load (which translation to apply).

I wonder if it's a bug that this library uses CurrentCulture to determine which JSON files to load. Logically it has to use CurrentUICulture.

This is the code I'm talking about:

var languageTag = Thread.CurrentThread.CurrentCulture.IetfLanguageTag;

Does this already support saveMissing and updateMissing backend configuration?

Hello i've tryed to look at the code and search for docs but it doesn't seems to me that this library already supports the i18next saveMissing, and updateMissing, backend configurrations, which allows the browser to signal missing keys (and the server should create them in the json file so they will be ready to be translated.

I'm i missing something? if the feature is missing i can probably contribute to the project implementing it. just let me know if i've missed it or there is at least something already implemented so i can pick up from there.

Thanks.

Problem with JsonFileBackend usage: Unable to retrieve translated values

Issue Description:

When using the provided code snippet with the JsonFileBackend method in I18NextNet, I'm encountering an issue where the translation returns the key instead of the value from the JSON file.

Steps to Reproduce:

  1. Use the following code snippet:
private async Task Translate()
{
    try
    {
        var backend = new JsonFileBackend();
        await SetupJsonBackend(backend);
        var translator = new DefaultTranslator(backend);
        var i18Next = new I18NextNet(backend, translator);
        //set language to english
        i18Next.Language = "en";
        var enText = i18Next.T("key1");
    }
    catch (Exception ex)
    {
    }
}

private async Task SetupJsonBackend(JsonFileBackend backend)
{
    try
    {
        await backend.LoadNamespaceAsync("en", "en.json");
    }
    catch (Exception ex)
    {
    }
}
  1. Ensure that the JSON file exists at the specified path (en.json).
  2. Confirm that the JSON file contains the correct structure and the translation key-value pair.
  3. Execute the code and observe the returned translation.

Expected Behavior:

The translation should return the value associated with the specified key from the JSON file.

Actual Behavior:

The translation returns the key itself instead of the associated value. (key1)

Additional Information:

I have verified the correctness of the JSON file and ensured that it contains the expected key-value pair.
There are no exceptions thrown during the loading of the JSON file or the translation process.
I have debugged the code and confirmed that the language is correctly set to "en" before retrieving the translation.

Environment:

Operating System: Windows 10 Pro 22H2 19045.4046
.NET Framework Version: 4.6.1
I18NextNet Version: 1.0.0

Note:

I also wanted to confirm whether the provided JSON file is grammatically correct. It contains the following key-value pair:

{
    "key1": "Good morning"
}

Thank you for your assistance in resolving this issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.