LibreTranslate/libretranslate/locales.py

34 lines
1 KiB
Python
Raw Normal View History

2023-01-04 20:36:26 +00:00
import os
2023-01-05 18:12:35 +00:00
import json
2023-01-04 20:36:26 +00:00
from functools import cache
2023-01-04 22:54:07 +00:00
from flask_babel import gettext as _
2023-01-05 18:12:35 +00:00
from flask_babel import lazy_gettext as _lazy
2023-01-04 22:54:07 +00:00
from markupsafe import escape, Markup
2023-01-04 20:36:26 +00:00
@cache
def get_available_locales():
locales_dir = os.path.join(os.path.dirname(__file__), 'locales')
dirs = [os.path.join(locales_dir, d) for d in os.listdir(locales_dir)]
2023-01-04 22:54:07 +00:00
return ['en'] + [os.path.basename(d) for d in dirs if os.path.isdir(os.path.join(d, 'LC_MESSAGES'))]
# Javascript code should use _e instead of _
def gettext_escaped(text, **variables):
2023-01-05 18:12:35 +00:00
return json.dumps(_(text, **variables))
2023-01-04 22:54:07 +00:00
# HTML should be escaped using _h instead of _
def gettext_html(text, **variables):
# Translate text without args
s = str(escape(_(text)))
v = {}
if variables:
for k in variables:
if hasattr(variables[k], 'unescape'):
v[k] = variables[k].unescape()
else:
v[k] = Markup(variables[k])
# Variables are assumed to be already escaped and thus safe
return Markup(s if not v else s % v)