I recently recognized that when I render a “dynamic” template using render_to_string("{% load i18n %}<div>{% translate "foo" %}</div>"), Django’s makemessages (gettext) does not find the translateable string “foo”. So it is not available in a .po file.
And if I put it there manually, with the next makemessages run, the translation is marked as obsolete and commented out.
Should I file a bug at Django? I need this behaviour.
Sure, when compiling dynamic content, It can’t be translated automatically. I could even write render_to_string(my_string_var) - but even then - it is not translated…
If you want makemessages to extract such string in the code instead of a real template, then you have to use one of the gettext syntax for the code, for example adding a line like gettext_noop("foo") somewhere else in the file. See Translation | Django documentation | Django
You may also try using the _("foo") syntax in your template snippet, but it will not work for all use cases.
Sure. I know that I can add a _(“foo”) for each string in the template snippet, additionally. But that is not what I want. I want to add this feature to django if necessary. Else I’d have to put each translated string twice in the code, once in the inline template, and once outside of it.
In fact, I am using tetra, and there you define inline templates:
in short:
class FooComponent(Component):
template = """
<div>{% translate "foo" %}</div>
"""
Tetra creates that component automatically from the string. And I want to add translatability to it.
Any hints on how gettext/makemessages work here? I had a look at the code, and it is quite file centric…
One Idea would be to parse the string and extract all translated string parts, adding a bunch of gettext_noop calls into a file that itself is then parsed again. Sounds creepy, but Tetra creates js files on the fly as well.
One could override the translate templatetag too, to create that strings…
I have doubts that Django will accept changing the way it detects translatable strings, as your use case is rather niche. I guess you will have to develop your own solution to this problem.