Gettext translations are not extracted when using a dynamic backend

Hello everyone!

I am developing a library that contains translations. Users of this library can define a gettext backend in the config.exs script used by my library. Gettext provides functions that take a backend as a parameter. I want to use these functions to translate text in my library, but the translations are not extracted by the mix gettext.extract task.

Suppose I have a module DemoWeb.Gettext with use Gettext in it:

If I have this function in my code, everything works as expected and the translations are extracted when the mix task runs:

DemoWeb.Gettext.dgettext("domain", "translation")

However, when I pass the backend as a parameter, the translation is not extracted:

Gettext.dgettext(DemoWeb.Gettext, "domain", "translation")

Is this because in this function, which accepts a dynamic backend, gettext does not know which backend is used at compile time, because it could be dynamic, and therefore cannot extract the translations?

Is there a better way to integrate gettext into a library or automatically extract translations with a backend defined in the config.exs script?

Thanks in advance. I appreciate any help!

The MyApp.Gettext.*_noop set of macros are designed to help in this situation. They mark the messages for extraction but do not otherwise include any code in your module.

I think the right approach is:

  • Define a Gettext backend in your library in your own namespace
  • Call MyLib.Gettext.dgettext_noop("domain, "message") for each message you want to be extracted.
  • Call the Gettext.dgettext(DemoWeb.Gettext, "domain", "translation") function as you normally would.

This ends up with two calls per message but one is a macro invoked at compile time (to extract the messages only) and the other is a function invoked at runtime to perform the translation.

2 Likes