3

Is there a way for me to include flask jinja enclosed babel translations inside of my javascript file and load it in as if it was a static file? Or is the only way for me to do this to include this part of my code in the .html template file? I'm asking because I want to abstract this part of my code out so it can be reused in other areas, but if I do this, I lose the translations and am not able to obtain necessary information.

Please advice. I want to import javascript file but also be able to use

var x = {{_('translation here')}}

inside of my javascript file and also be able to pull out the translations via babel to be later internationalized via .po file.

Thanks! Cheers

desertnaut
  • 57,590
  • 26
  • 140
  • 166
user805981
  • 9,979
  • 8
  • 44
  • 64

2 Answers2

2

I tried a lot to make flask babel translate texts from my js file and just import the script to the html with a:

<script src="myscripts.js"></script>

so I found some good links:

  1. Flask-Babel localized strings within js

  2. Babel.cfg

So I understood that I need to make my own babel.cfg file: that includes [javascript: /.js] in the header.

Although I did it, and executed the code:

pybabel extract -F babel.cfg -o messages.pot

It still didn't translated from javascript... so for now I am putting the script in an html:

<html>
<script>
//my script with {{_('translating')}}
</script>
</html>

And including this html where I need the script with an:

{% include 'myscript.html' %}

I know it is horrible, but is the only think that is working for me now

Dinidiniz
  • 771
  • 9
  • 15
-2

To use jinja notation in js you should wrap it with "":

use:

var x = "{{_('translation here')}}"

or:

var x = "{{gettext('translation here')}}"

But I think the standard way is to pass the translation from back-end:

from flask_babel import gettext
foo = gettext(a)
return render_template(HTML, a=a)
YakovL
  • 7,557
  • 12
  • 62
  • 102