From 2d5749007a29ff7448af47273e2d326e565687ea Mon Sep 17 00:00:00 2001 From: Kiril Kovachev Date: Mon, 14 Oct 2024 11:49:16 +0100 Subject: [PATCH] Add localization support --- kanken_online/__init__.py | 9 +++++++- kanken_online/lang.py | 35 ++++++++++++++++++++++++++++++ kanken_online/templates/base.html | 12 +++++----- kanken_online/templates/kanji.html | 2 +- 4 files changed, 50 insertions(+), 8 deletions(-) create mode 100644 kanken_online/lang.py diff --git a/kanken_online/__init__.py b/kanken_online/__init__.py index 4a8489e..a86262f 100644 --- a/kanken_online/__init__.py +++ b/kanken_online/__init__.py @@ -1,5 +1,5 @@ import os -from flask import Flask, render_template +from flask import Flask, render_template, g from pathlib import Path from .auth import login_required @@ -69,4 +69,11 @@ def create_app(test_config=None): app.register_blueprint(auth.blueprint) app.register_blueprint(api.blueprint) + from . import lang + + def use_english(text_id: str): + return lang.localize(text_id, lang.JAPANESE) + app.jinja_env.globals.update(localize=use_english) + + return app \ No newline at end of file diff --git a/kanken_online/lang.py b/kanken_online/lang.py new file mode 100644 index 0000000..287b5d7 --- /dev/null +++ b/kanken_online/lang.py @@ -0,0 +1,35 @@ +EXISTING_STRINGS = { + "kanken_online", + "options", + "log_in", + "register", + "log_out" +} + +ENGLISH = { + "kanken_online": "KankenOnline", + "options": "Options", + "log_in": "Log in", + "register": "Register", + "log_out": "Log out", + "kanji": "Kanji" +} + +JAPANESE = { + "kanken_online": "漢検オンライン", + "options": "設定", + "log_in": "ログイン", + "register": "登録", + "log_out": "ログアウト", + "kanji": "漢字" +} + +LANGUAGES = [ + ENGLISH, + JAPANESE +] + +assert all(all(key in lang for key in EXISTING_STRINGS) for lang in LANGUAGES) # Ensure all strings are mapped for all existing languages + +def localize(text_id: str, language: dict[str, str]) -> str: + return language[text_id] diff --git a/kanken_online/templates/base.html b/kanken_online/templates/base.html index dd5de48..00e46ff 100644 --- a/kanken_online/templates/base.html +++ b/kanken_online/templates/base.html @@ -2,22 +2,22 @@ - {% block title %}{% endblock %} - KankenOnline + {% block title %}{% endblock %} - {{ localize("kanken_online") }} {% block styles %}{% endblock %} {% block scripts %}{% endblock %} diff --git a/kanken_online/templates/kanji.html b/kanken_online/templates/kanji.html index 22c576c..686a86a 100644 --- a/kanken_online/templates/kanji.html +++ b/kanken_online/templates/kanji.html @@ -3,7 +3,7 @@ {% block scripts %}{%endblock %} {% block header %} -

{% block title %}Kanji - {{ kanji.character }}{% endblock %}

+

{% block title %}{{localize("kanji")}} - {{ kanji.character }}{% endblock %}

{% endblock %} {% block content %}