user805981
user805981

Reputation: 11069

babel flask jinja javascript hell

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

Upvotes: 3

Views: 1227

Answers (2)

Dinidiniz
Dinidiniz

Reputation: 811

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

Upvotes: 3

Syed Mohammad Hosseini
Syed Mohammad Hosseini

Reputation: 522

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)

Upvotes: -2

Related Questions