Dynamically generated offers for a multilingual ASP.NET website

We plan to add multilingual support to our ASP.NET website. I understand the general process of pulling strings from resource files based on the current culture, but what is the best way to handle the following situation?

Let's say that we want to display to the user how many stack overflow messages they made today. Let's say that iis the number of messages. If you just worked in English, you would have the following code.

if(i == 1)
{
    postCountText = "You have made " + i + " post today";
} else {
    postCountText = "You have made " + i + " posts today";
}

So, the text is created based on whether we are dealing with single or multiple messages.

What if we want to create post text in any other language? Obviously, we cannot have many conditional statements, for example, above, so the lines in the resource files must work automatically to create the desired output text. In another language, it may happen that not only the word changes post(s), but possibly the word todayas you move between singular and plural.

The only idea I have had so far is to save two lines in an external resource file, one for the singular and one for the plural, and then apply to them String.Formatto insert the message counter in the right place.

i.e. The resource file for the English language will contain the following two lines:

singlePostCount : "You have made {0} post today"

pluralPostCount : "You have made {0} posts today"

Then, to create the output text, I would have the following code:

if(i == 1)
{
    postCountText = String.Format(GetResourceString("singlePostCount"), i);
} else {
    postCountText = String.Format(GetResourceString("pluralPostCount"), i);
}

. , , , ? .

+3
3

( 3 ).
, :

" : {0}"

+3

( Sachin post, "": -)

haarrrgh " : {0}". "", .

( 0, 1, 2, , , 10 1 (1, 51, 4231 ), , 100 20 99). ( ) . \multipals.xml CLDR. ( core.zip ftp://ftp.unicode.org/Public/cldr/1.6.1/)

: http://www.mihai-nita.net/article.php?artID=20060430a

+1

Use a StringTemplate , as this is the best way to deal with this situation.

It is as simple as the following:

Suppose you have a template file like sample.st:

Dear $user$ you have exceeded the usage. Your current balance is $amount$

Just add the following code:

StringTemplateGroup group =  new StringTemplateGroup("myGroup", "C:\\Templates", DefaultTemplateLexer.class);
StringTemplate Message = group.getInstanceOf("sample");
Message.setAttribute("user", "Sam");
Message.setAttribute("amount", "100");
Message.toString();

Edit: You can use the function for plurals as follows:

Dear $user$ you have  $posts$ post$plural$

StringTemplate Message = group.getInstanceOf("sample");
Message.setAttribute("user", "Sam");
Message.setAttribute("post", post);

Message.setAttribute("plural", Getplural(post));
Message.toString();

String getplural(int i)
{

If i >1
Return "s";
}

More details here .

0
source

Source: https://habr.com/ru/post/1702909/


All Articles