Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include Variables in Localized Strings?

I'm trying to display a message to the user along the lines of:

"User 5 could not be added"

But how can I add variables to a string that is being placed in a .resx file? I've trying searching for things like "Variables in Localization" "Globalization with Variables" etc, but came up dry.

If I weren't localizing I would write:

Console.Write("User " + userNum + " could not be added");

How can this be accomplished with resources?

like image 351
DTI-Matt Avatar asked Jun 08 '12 20:06

DTI-Matt


People also ask

What does localized string mean?

There are two categories of localized strings: the strings included in the installation package's UI, common to every MSI file. the strings included in your project, that are particular to the current project: the name of your application, file names, registry values, properties etc.

What is localized string key?

The key used to look up an entry in a strings file or strings dictionary file.

How does NSLocalizedString work?

NSLocalizedString is a Foundation macro that returns a localized version of a string. It has two arguments: key , which uniquely identifies the string to be localized, and comment , a string that is used to provide sufficient context for accurate translation.


2 Answers

You can't do this directly.

What you can do is place a token - a specific string that can be replaced with string.Replace with the value of the variable.

A good candidate for this would be the built in string formatting:

Console.Write(string.Format("User {0} could not be added", userNum));

Assuming userNum has the value 5, the result would be:

User 5 could not be added

You can localize this string with the composite format specifiers.

like image 169
Oded Avatar answered Sep 30 '22 20:09

Oded


In teams where I've done internationalization, we generally also created a resource for the format string, something like USER_COULD_NOT_BE_ADDED_FORMAT, and called String.Format (or your environment's equivalent) by passing that resource's value as the format pattern.

Then you'll do Console.Write(String.Format(resourceManager.GetString("USER_COULD_NOT_BE_ADDED_FORMAT"), userNum));

Most localizers either have training in the format strings used by the system they are localizing, or they are provided with guidance in the localization kit that you provide them. So this is not, for example, as high a barrier as making them modify code directly.

You generally need to add a loc comment to the resource ID to explain the positional parameters.

like image 35
JasonTrue Avatar answered Sep 30 '22 19:09

JasonTrue