Add localization support

This commit is contained in:
Kiril Kovachev 2024-10-14 11:49:16 +01:00
parent 6614d6344a
commit 2d5749007a
4 changed files with 50 additions and 8 deletions

View File

@ -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

35
kanken_online/lang.py Normal file
View File

@ -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]

View File

@ -2,22 +2,22 @@
<html>
<head>
<title>{% block title %}{% endblock %} - KankenOnline</title>
<title>{% block title %}{% endblock %} - {{ localize("kanken_online") }}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
{% block styles %}{% endblock %}
{% block scripts %}{% endblock %}
</head>
<body>
<nav>
<h1>KankenOnline</h1>
<h1>{{ localize("kanken_online") }}</h1>
<ul>
{% if g.user %}
<li><span>{{ g.user['username'] }}</span>
<li><a href="{{ url_for('options') }}">Options</a>
<li><a href="{{ url_for('auth.logout') }}">Log Out</a>
<li><a href="{{ url_for('options') }}">{{ localize("options") }}</a>
<li><a href="{{ url_for('auth.logout') }}">{{ localize("log_out") }}</a>
{% else %}
<li><a href="{{ url_for('auth.register') }}">Register</a>
<li><a href="{{ url_for('auth.login') }}">Log In</a>
<li><a href="{{ url_for('auth.register') }}">{{ localize("register") }}</a>
<li><a href="{{ url_for('auth.login') }}">{{ localize("log_in") }}</a>
{% endif %}
</ul>
</nav>

View File

@ -3,7 +3,7 @@
{% block scripts %}<script src="/static/kanji.js" defer></script>{%endblock %}
{% block header %}
<h1>{% block title %}Kanji - {{ kanji.character }}{% endblock %}</h1>
<h1>{% block title %}{{localize("kanji")}} - {{ kanji.character }}{% endblock %}</h1>
{% endblock %}
{% block content %}