When dealing with strings we often experience challenges to insert some placeholders or to completely replace the string content depending on some variables.
One of the best solutions I have found for this is using ICU message format. It allows us to define:
-
placeholders, in a common way
{name}
-
plural, with
{count, plural, one{1 apple} other{{count} apples}}
-
custom selects, with
{gender, select, male{His} female{Her} other{Their}}
Plurals are especially important, those can not be easily defined programmatically with if
conditions since plural rules differ among languages. Using ICU message plurals allow us to define only those plural variations that are applicable for the given language, and the framework/package automatically applies those variations depending on the variable (count
in our case).
Luckily, ICU messages are supported in some popular frameworks or packages:
And I see more packages is starting to support it.
Although ICU formats can vary a bit among those implementations, the foundation is the same.
The only disadvantage that I have found with ICU messages is that sometimes it can be a bit hard to spot errors in its structure. For instance, missing second closing curly bracket for plural, missing comma, or similar. Using online editor for ICU message format can detect such issues, or make it pretty printed for easier editing.
However, I couldn't find a better way to define those plural and select cases that are easier to maintain than with this structure.
I believe many of you are aware of ICU messages, but I still see some developers use if
conditions in the code for plurals which does not work, concatenate a string that contains variables, or similar. ICU messages make it much easier.
Top comments (1)
I have now problems in my project with message-format because the library as it is now doesn’t conform to content security policy (unsafe-eval) because it creates a new function. If anybody have a solution let me know.