Question

Using django, with jinja2 for rendering & babel for message extraction

I have some js files that need to be internationalized. I haven't been able to figure out a syntax for extracting messages from them which would also let jinja2 render them. Either jinja2 has to learn to read an extractable syntax, or I have to extract from something jinja2 can render. (Or, do this another way entirely)

Extracting

If I mark messages in the js with

gettext('message')

It extracts just fine.

Rendering

But jinja2 won't replace gettext calls in js (I'm rendering the js templates with jinja2 before returning them) - it needs something like

{% trans %}message{% endtrans %}

But, that syntax can't be used to extract messages.

Babel is using the function extract_javascript from babel.messages to extract messages, which doesn't look equipeed to handle this type of tag.

Was it helpful?

Solution

Well, it looks like I can just do:

{{gettext("message")}} 

(without defining gettext)

in the JS and babel will extract & jinja2 will replace it ok.

Watch out for quotes, though. You can't do:

'{{gettext("message")}}'

because extract_javascript will not read it. But, you can just put the quotes inside, as long as you render them safely:

{{gettext("'message'")|safe}}

So have your translators make sure to leave quotations wherever they find them in the original.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top