Flask-Babel localized strings within js

2024/10/13 16:22:09

I'm pretty new to both Python and Flask (with Jinja2 as template engine) and I am not sure I am doing it the right way. I am using Flask-Babel extension to add i18n support to my web application. I want to get localized strings from my js code, for instance:

var helloWorld = gettext('Hello, world');
console.log(helloWorld); //should log a localized hello world message

For this, I configured babel (babel.cfg):

[python: **/**.py]
[jinja2: **/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_
[javascript: **/**.js]
encoding = utf-8

And its initialization is (imports omitted for simplicity):

#main Flask app
app = Flask(__name__)#localization
babel = Babel(app)LANGUAGES = {'ca': 'Catalan','en': 'English','de': 'Deutsch','es': 'Español','fi': 'Finnish','it': 'Italian'
}@babel.localeselector
def get_locale():return request.accept_languages.best_match(LANGUAGES.keys())#some more stuff...

Babel identifies that string when building the POT/PO language files, but it seems I can't access these localized strings from js code since gettext function is not defined. It seems like Jinja2 is ignoring this part.

Any hints?

Answer

I have finally found a solution, although I am not sure it is the way to go. The idea is to wrap the javascript code within an html template, which is interpretated by Jinja2 before it is rendered and apply a custom Jinja2 filter to get rid of some minor issues. I tried to keep js files separately but it did not work.

It seems that gettext function can be used like so:

var helloWorld = {{gettext('Hello, world')}};

But then, no quotes are inserted, and hence, js interpreter throws an error:

var helloWorld = Hello, world;

That's why I have finally applied a custom filter. A working example would be as follows.

hello_world.html:

<script type="text/javascript">var x = {{gettext('Hello, world')|generate_string|safe}};console.log(x);    //logs the localized hello world message
</script>

app.py:

#Jinja2 filters
from jinja2 import evalcontextfilter, Markup#Mind the hack! Babel does not work well within js code
@app.template_filter()
@evalcontextfilter
def generate_string(eval_ctx, localized_value):if localized_value is None:return ""else:return Markup("\"" + localized_value + "\"").unescape()

Hope this helps!

https://en.xdnf.cn/q/69513.html

Related Q&A

a (presumably basic) web scraping of http://www.ssa.gov/cgi-bin/popularnames.cgi in urllib

I am very new to Python (and web scraping). Let me ask you a question. Many website actually do not report its specific URLs in Firefox or other browsers. For example, Social Security Admin shows popul…

Why is tuple being returned?

I have the following:tableNumber = session.query(TABLE.TABLESNUMBER).filter_by(TABLESID=self.TABLESID).first() return str(tableNumber)This is my TABLE class:class TABLE(Base):.... TABLESID =…

How to assert both UserWarning and SystemExit in pytest

Assert UserWarning and SystemExit in pytestIn my application I have a function that when provided with wrong argument values will raise a UserWarnings from warnings module and then raises SystemExit fr…

Distinguish button_press_event from drag and zoom clicks in matplotlib

I have a simple code that shows two subplots, and lets the user left click on the second subplot while recording the x,y coordinates of those clicks.The problem is that clicks to select a region to zoo…

String reversal in Python

I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?I a…

Python: passing functions as arguments to initialize the methods of an object. Pythonic or not?

Im wondering if there is an accepted way to pass functions as parameters to objects (i.e. to define methods of that object in the init block).More specifically, how would one do this if the function de…

Encrypt and Decrypt by AES algorithm in both python and android

I have python and android code for AES encryption. When I encrypt a text in android, it decrypt on python successfully but it can’t decrypt in android side. Do anyone have an idea?Python code :impo…

How to conditionally assign values to tensor [masking for loss function]?

I want to create a L2 loss function that ignores values (=> pixels) where the label has the value 0. The tensor batch[1] contains the labels while output is a tensor for the net output, both have a …

Assign Colors to Lines

I am trying to plot a variable number of lines in matplotlib where the X, Y data and colors are stored in numpy arrays, as shown below. Is there a way to pass an array of colors into the plot function,…

How to display multiple annotations in Seaborn Heatmap cells

I want seaborn heatmap to display multiple values in each cell of the heatmap. Here is a manual example of what I want to see, just to be clear:data = np.array([[0.000000,0.000000],[-0.231049,0.000000]…