Lazy interpolation in Gettext

Just to recap:

If you use interpolation to construct a string, and you provide it with missing keys, then it returns an error telling you which keys are missing.

However, I need to use Gettext dynamically, and I would like it to do something a little different: if the key “key” is not present, then I would like it to return the string with place holder text “{key}”.

For example, instead of this:

Localisation.Gettext.lgettext("en", "hello_world", "score-message", %{})
{:error, "missing interpolation keys: score"}

I would like it to return this:

Localisation.Gettext.lgettext("en", "hello_world", "score-message", %{})
{:ok, "You have scored {score} points."}

However, it seems my only options are:

  1. don’t use interpolation and do my own parsing on strings stored as “You have scored {score} points.” instead of “You have scored %{score} points.”.
  2. catching the error, parsing the message for the missing keys, creating a new map with default values and then passing this back in (which is obviously bad).
  3. branching the project and making substantial modifications to interpolation.ex, etc…

I’m wondering if anyone has any suggestions?

1 Like