I18n segura para o tipo .NET
Slang.net é uma porta .NET da gíria da comunidade Dart/Flutter com novos recursos (como formato de string).
Você pode ver como os arquivos gerados gerais, en e de look
Instale a biblioteca como um pacote NUGET:
Install-Package dotnet add package Slang.NetO arquivo importante deve terminar com ".i18n.json". Isso é necessário para que o ORERCEGERERATER não rastreie as alterações em outros arquivos adicionais.
i18n/strings_en.i18n.json ou i18n/strings_en-US.i18n.json ou i18n/strings.i18n.json (para cultura base)
{
"screen" : {
"locale1" : " Locale 1 "
}
} i18n/strings_ru.i18n.json ou i18n/strings_ru-RU.i18n.json
{
"screen" : {
"locale1" : " Локаль 1 "
}
} slang.json
{
"base_culture" : " en " // or "en-EN"
}Recomendação É recomendável especificar o código do país, como "En-US", para a funcionalidade adequada ao formatar seqüências, especialmente se você estiver recuperando a lista de culturas de culturas suportadas.
< 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 1ou
< MenuItem Header = " {Binding Root.Screen.Locale1, Source={x:Static localization:Strings.Instance}} " />Você pode especificar parâmetros passados em tempo de execução ..
{
"Hello" : " Hello {name} "
}O código gerado ficará assim:
/// In en, this message translates to:
/// **"Hello {name}"**
public virtual string Hello ( object name ) => $ "Hello { name } " ; Os parâmetros são digitados como object por padrão. Isso é conveniente porque oferece máxima flexibilidade.
Você pode especificar o tipo usando duas opções de sintaxe: 1 - Simples:
{
"greet" : " Hello {name: string}, you are {age: int} years old "
}2 - Usando um espaço reservado, que permite especificar uma string de tipo ou formato (consulte o formato da string).
{
"greet2" : " Hello {name}, you are {age} years old " ,
"@greet2" : {
"placeholders" : {
"name" : {
"type" : " string "
},
"age" : {
"type" : " int "
}
}
}
}O código gerado ficará assim:
/// 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" ;Você pode adicionar comentários aos seus arquivos de tradução.
{
"@@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 "
}
}
}O código gerado ficará assim:
/// The submit button shown at the bottom
///
/// In ru, this message translates to:
/// **"Submit"**
public virtual string Button => "Submit" ; Esta biblioteca suporta o formato de incorporação via ToString(format) para os seguintes tipos: int , long , double , decimal , float , DateTime , DateOnly , TimeOnly , TimeSpan . Para outros tipos, a sequência do formato é passada através 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:25O código gerado ficará assim:
/// 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 o conceito definido aqui.
Alguns idiomas têm suporte para fora da caixa. Veja aqui.
Os plurais são detectados pelas seguintes palavras -chave: 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. O código gerado ficará assim:
public virtual string Apple ( int n ) => PluralResolvers . Cardinal ( "en" ) ( n ,
one : $ "I have { n } apple." ,
other : $ "I have { n } apples." ) ;Os plurais detectados são cardeais por padrão.
Para especificar ordinais, você precisa adicionar o 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 padrão, o nome do parâmetro é n . Você pode alterar isso adicionando um 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' Você pode definir o parâmetro padrão globalmente usando PluralParameter .
[ Translations (
InputFileName = "strings" ,
PluralParameter = "count" ) ]
internal partial class Strings ; Você pode vincular uma tradução a outra. Adicione o prefixo @: seguido pelo caminho absoluto à tradução desejada.
{
"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.O código gerado ficará assim:
/// 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, você pode escapar das traduções vinculadas ao redor do caminho com {} :
{
"fields" : {
"name" : " my name is {firstName} "
},
"introduce" : " Hello, @:{fields.name}inator "
}Você também pode colocar listas nas 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"O código gerado ficará assim:
public virtual List < dynamic > NiceList => [
"hello" ,
"nice" ,
new [ ] {
"first item in nested list" ,
"second item in nested list" ,
} ,
new Feature1NiceList0i3Ru ( _root ) ,
new Feature1NiceList0i4Ru ( _root ) ,
] ;Você pode acessar cada tradução usando teclas de string.
Adicione o modificador (map) .
{
"a(map)" : {
"helloWorld" : " hello "
},
"b" : {
"b0" : " hey " ,
"b1(map)" : {
"hiThere" : " hi "
}
}
}Agora você pode acessar traduções usando chaves:
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"O código gerado ficará assim:
/// In ru, this message translates to:
/// **"hey"**
public virtual string B0 => "hey" ;
public virtual IReadOnlyDictionary < string , string > B1 => new Dictionary < string , string > {
{ "hiThere" , " hi "},
} ; Aproveite o GPT para internacionalizar seu aplicativo com traduções com reconhecimento de contexto.
Instale a CLI da gíria:
dotnet tool install --global Slang.CLIEm seguida, adicione a seguinte configuração em sua gíria.json:
{
"base_culture" : " en " ,
"gpt" : {
"base_culture" : " ru " ,
"model" : " gpt-4o-mini " ,
"description" : " Showcase for Slang.Net.Gpt "
}
}Em seguida, use Slang-GPT:
slang gpt --target=en --api-key= < api-key >Veja mais: documentação