Tipo Safe I18N para .NET
Slang.net es un puerto .NET de la jerga de la comunidad Dart/Flutter con nuevas características (como formato de cadena).
Puede ver cómo los archivos generados generales, EN y De se ven
Instale la biblioteca como un paquete Nuget:
Install-Package dotnet add package Slang.NetEl archivo importante debe terminar con ".i18n.json". Esto es necesario para que el SourceGenerator no rastree los cambios en otros archivos adicionales.
i18n/strings_en.i18n.json o i18n/strings_en-US.i18n.json o i18n/strings.i18n.json (para cultura base)
{
"screen" : {
"locale1" : " Locale 1 "
}
} i18n/strings_ru.i18n.json o i18n/strings_ru-RU.i18n.json
{
"screen" : {
"locale1" : " Локаль 1 "
}
} slang.json
{
"base_culture" : " en " // or "en-EN"
}Recomendación Se recomienda especificar el código de país, como "EN-US", para una funcionalidad adecuada al formatear cadenas, especialmente si recuperará la lista de culturas de las culturas de apoyo.
< ItemGroup >
< AdditionalFiles Include = " i18n*.i18n.json " />
< AdditionalFiles Include = " slang.json " />
</ ItemGroup > [ Translations ( InputFileName = "strings" ) ]
public partial class Strings ; Strings . SetCulture ( new CultureInfo ( "ru-RU" ) ) ;
Console . WriteLine ( Strings . Instance . Root . Screen . Locale1 ) ; // Локаль 1
Strings . SetCulture ( new CultureInfo ( "en-US" ) ) ;
Console . WriteLine ( Strings . Instance . Root . Screen . Locale1 ) ; // Locale 1o
< MenuItem Header = " {Binding Root.Screen.Locale1, Source={x:Static localization:Strings.Instance}} " />Puede especificar parámetros pasados en tiempo de ejecución.
{
"Hello" : " Hello {name} "
}El código generado se verá así:
/// In en, this message translates to:
/// **"Hello {name}"**
public virtual string Hello ( object name ) => $ "Hello { name } " ; Los parámetros se escriben como object por defecto. Esto es conveniente porque ofrece la máxima flexibilidad.
Puede especificar el tipo que usa dos opciones de sintaxis: 1 - Simple:
{
"greet" : " Hello {name: string}, you are {age: int} years old "
}2 - Uso de un marcador de posición, que le permite especificar un tipo o cadena de formato (consulte el formato de cadena).
{
"greet2" : " Hello {name}, you are {age} years old " ,
"@greet2" : {
"placeholders" : {
"name" : {
"type" : " string "
},
"age" : {
"type" : " int "
}
}
}
}El código generado se verá así:
/// In ru, this message translates to:
/// **"Hello {name}, you are {age} years old"**
public virtual string Greet ( string name , int age ) => $ "Hello { name } , you are { age } years old" ;Puede agregar comentarios a sus archivos de traducción.
{
"@@locale" : " en " , // fully ignored
"mainScreen" : {
"button" : " Submit " ,
// ignored as translation but rendered as a comment
"@button" : " The submit button shown at the bottom " ,
// or use
"button2" : " Submit " ,
"@button2" : {
"description" : " The submit button shown at the bottom "
}
}
}El código generado se verá así:
/// The submit button shown at the bottom
///
/// In ru, this message translates to:
/// **"Submit"**
public virtual string Button => "Submit" ; Esta biblioteca admite el formato de incrustación a través de ToString(format) para los siguientes tipos: int , long , double , decimal , float , DateTime , DateOnly , TimeOnly , TimeSpan . Para otros tipos, la cadena de formato se pasa a través de string.Format(format, locale) .
{
"dateExample" : " Date {date} " ,
"@dateExample" : {
"placeholders" : {
"date" : {
"type" : " DateTime " ,
"format" : " dd MMMM HH:mm "
}
}
}
} String s = Strings . Instance . Root . DateExample ( DateTime . Now ) ; // Date 17 October 22:25El código generado se verá así:
/// In ru, this message translates to:
/// **"Date {date}"**
public virtual string DateExample ( DateTime date )
{
string dateString = date . ToString ( "dd MMMM HH:mm" ) ;
return $ "Date { dateString } " ;
}Esta biblioteca usa el concepto definido aquí.
Algunos idiomas tienen soporte fuera de la caja. Ver aquí.
Los plurales se detectan mediante las siguientes palabras clave: zero , one , two , few , many , other .
{
"someKey" : {
"apple" : {
"one" : " I have {n} apple. " ,
"other" : " I have {n} apples. "
}
}
} String a = Strings . Instance . Root . SomeKey . Apple ( n : 1 ) ; // I have 1 apple.
String b = Strings . Instance . Root . SomeKey . Apple ( n : 2 ) ; // I have 2 apples. El código generado se verá así:
public virtual string Apple ( int n ) => PluralResolvers . Cardinal ( "en" ) ( n ,
one : $ "I have { n } apple." ,
other : $ "I have { n } apples." ) ;Los plurales detectados son cardenales de forma predeterminada.
Para especificar Ordinales, debe agregar el modificador (ordinal) .
{
"someKey" : {
"apple(cardinal)" : {
"one" : " I have {n} apple. " ,
"other" : " I have {n} apples. "
},
"place(ordinal)" : {
"one" : " {n}st place. " ,
"two" : " {n}nd place. " ,
"few" : " {n}rd place. " ,
"other" : " {n}th place. "
}
}
} Por defecto, el nombre del parámetro es n . Puede cambiar eso agregando un modificador.
{
"someKey" : {
"apple(param=appleCount)" : {
"one" : " I have one apple. " ,
"other" : " I have multiple apples. "
}
}
} String a = Strings . Instance . Root . SomeKey . Apple ( appleCount : 1 ) ; // notice 'appleCount' instead of 'n' Puede establecer el parámetro predeterminado a nivel mundial usando PluralParameter .
[ Translations (
InputFileName = "strings" ,
PluralParameter = "count" ) ]
internal partial class Strings ; Puede vincular una traducción a otra. Agregue el prefijo @: seguido de la ruta absoluta a la traducción deseada.
{
"fields" : {
"name" : " my name is {firstName} " ,
"age" : " I am {age} years old "
},
"introduce" : " Hello, @:fields.name and @:fields.age "
} String s = Strings . Instance . Root . Introduce (firstName : "Tom" , age : 27 ); // Hello, my name is Tom and I am 27 years old.El código generado se verá así:
/// In ru, this message translates to:
/// **"Hello, {_root.Fields.Name(firstName: firstName)} and {_root.Fields.Age(age: age)}"**
public virtual string Introduce ( object firstName , object age ) => $ "Hello, { _root . Fields . Name ( firstName : firstName ) } and { _root . Fields . Age ( age : age ) } " ; Opcionalmente, puede escapar de las traducciones vinculadas rodeando la ruta con {} :
{
"fields" : {
"name" : " my name is {firstName} "
},
"introduce" : " Hello, @:{fields.name}inator "
}¡También puede colocar listas dentro de las listas!
{
"niceList" : [
" hello " ,
" nice " ,
[
" first item in nested list " ,
" second item in nested list "
],
{
"wow" : " WOW! " ,
"ok" : " OK! "
},
{
"aMapEntry" : " access via key " ,
"anotherEntry" : " access via second key "
}
]
} String a = Strings . Instance . Root . NiceList [ 1 ] ; // "nice"
String b = Strings . Instance . Root . NiceList [ 2 ] [ 0 ] ; // "first item in nested list"
String c = Strings . Instance . Root . NiceList [ 3 ] . Ok ; // "OK!"
String d = Strings . Instance . Root . NiceList [ 4 ] . AMapEntry ; // "access via key"El código generado se verá así:
public virtual List < dynamic > NiceList => [
"hello" ,
"nice" ,
new [ ] {
"first item in nested list" ,
"second item in nested list" ,
} ,
new Feature1NiceList0i3Ru ( _root ) ,
new Feature1NiceList0i4Ru ( _root ) ,
] ;Puede acceder a cada traducción con teclas de cadena.
Agregue el modificador (map) .
{
"a(map)" : {
"helloWorld" : " hello "
},
"b" : {
"b0" : " hey " ,
"b1(map)" : {
"hiThere" : " hi "
}
}
}Ahora puede acceder a traducciones usando claves:
String a = Strings . Instance . Root . A [ "helloWorld" ] ; // "hello"
String b = Strings . Instance . Root . B . B0 ; // "hey"
String c = Strings . Instance . Root . B . B1 [ "hiThere" ] ; // "hi"El código generado se verá así:
/// In ru, this message translates to:
/// **"hey"**
public virtual string B0 => "hey" ;
public virtual IReadOnlyDictionary < string , string > B1 => new Dictionary < string , string > {
{ "hiThere" , " hi "},
} ; Aproveche GPT para internacionalizar su aplicación con traducciones con el contexto.
Instale la jerga CLI:
dotnet tool install --global Slang.CLILuego agregue la siguiente configuración en su Slang.json:
{
"base_culture" : " en " ,
"gpt" : {
"base_culture" : " ru " ,
"model" : " gpt-4o-mini " ,
"description" : " Showcase for Slang.Net.Gpt "
}
}Luego use Slang-GPT:
slang gpt --target=en --api-key= < api-key >Ver más: Documentación