From bfbe848c011308f25099d4e3b2f4d6bc8b9ca20f Mon Sep 17 00:00:00 2001 From: Piero Toffanin Date: Thu, 5 Jan 2023 14:36:50 -0500 Subject: [PATCH] LT_LOCALE_LINK_TEMPLATE support --- libretranslate/app.py | 7 +++++-- libretranslate/locales.py | 15 +++++++++++++++ libretranslate/templates/index.html | 4 +++- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/libretranslate/app.py b/libretranslate/app.py index 53e8d01..44e685d 100644 --- a/libretranslate/app.py +++ b/libretranslate/app.py @@ -19,7 +19,8 @@ from flask_babel import Babel from libretranslate import flood, remove_translated_files, security from libretranslate.language import detect_languages, improve_translation_formatting -from libretranslate.locales import _, _lazy, get_available_locales, gettext_escaped, gettext_html, lazy_swag +from libretranslate.locales import (_, _lazy, get_available_locales, gettext_escaped, + gettext_html, lazy_swag, get_alternate_locale_links) from .api_keys import Database, RemoteDatabase from .suggestions import Database as SuggestionsDatabase @@ -285,7 +286,9 @@ def create_app(args): web_version=os.environ.get("LT_WEB") is not None, version=get_version(), swagger_url=SWAGGER_URL, - url_prefix=args.url_prefix + url_prefix=args.url_prefix, + current_locale=get_locale(), + alternate_locales=get_alternate_locale_links() ) @bp.route("/static/js/app.js") diff --git a/libretranslate/locales.py b/libretranslate/locales.py index 39ae708..5f51ca0 100644 --- a/libretranslate/locales.py +++ b/libretranslate/locales.py @@ -13,6 +13,21 @@ def get_available_locales(): return ['en'] + [os.path.basename(d) for d in dirs if os.path.isdir(os.path.join(d, 'LC_MESSAGES'))] +@cache +def get_alternate_locale_links(): + tmpl = os.environ.get("LT_LOCALE_LINK_TEMPLATE") + if tmpl is None: + return [] + + locales = get_available_locales() + result = [] + for l in locales: + link = tmpl.replace("{LANG}", l) + if l == 'en': + link = link.replace("en.", "") + result.append({ 'link': link,'lang': l }) + return result + # Javascript code should use _e instead of _ def gettext_escaped(text, **variables): return json.dumps(_(text, **variables)) diff --git a/libretranslate/templates/index.html b/libretranslate/templates/index.html index 86a70f7..f64e280 100644 --- a/libretranslate/templates/index.html +++ b/libretranslate/templates/index.html @@ -1,8 +1,10 @@ - + + {% for al in alternate_locales %} + {% endfor %} LibreTranslate - {{ _h("Free and Open Source Machine Translation API") }}