Skip to content

Commit

Permalink
Merge pull request #107 from Markus92/main
Browse files Browse the repository at this point in the history
fix(translations): populate translations with a fallback language
  • Loading branch information
hcvdwerf authored Oct 16, 2024
2 parents dc0ca52 + 43e482f commit 3d7a03d
Showing 1 changed file with 25 additions and 9 deletions.
34 changes: 25 additions & 9 deletions ckanext/gdi_userportal/logic/action/translation_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
#
# SPDX-License-Identifier: Apache-2.0

# -*- coding: utf-8 -*-
from ckan.plugins import toolkit
from typing import Any, List, Dict
from ckan.common import request, config
from dataclasses import dataclass
from typing import Any, Dict, List

from ckan.common import config, request

# -*- coding: utf-8 -*-
from ckan.plugins import toolkit

PACKAGE_REPLACE_FIELDS = [
"access_rights",
Expand All @@ -20,6 +21,7 @@
"theme",
]
RESOURCE_REPLACE_FIELDS = ["format"]
DEFAULT_FALLBACK_LANG = "en"


@dataclass
Expand All @@ -31,23 +33,37 @@ class ValueLabel:

def get_translations(values_to_translate: List) -> Dict[str, str]:
"""Calls term_translation_show action with a list of values to translate"""
language = _get_language()
translations = toolkit.get_action("term_translation_show")(
{}, {"terms": values_to_translate, "lang_codes": language}
pref_language = _get_language()
fallback_language = config.get("ckan.locale_default", DEFAULT_FALLBACK_LANG)

translation_table = toolkit.get_action("term_translation_show")(
{},
{
"terms": values_to_translate,
"lang_codes": (pref_language, fallback_language),
},
)

# First fill the dictionary with the fallback language
translations = {
transl_item["term"]: transl_item["term_translation"]
for transl_item in translations
for transl_item in translation_table
if (transl_item["lang_code"] == fallback_language)
}

# Override with preferred language
for transl_item in translation_table:
if transl_item["lang_code"] == pref_language:
translations[transl_item["term"]] = transl_item["term_translation"]

return translations


def _get_language() -> str:
"""
Tries to get default language from environment variables/ckan config, defaults to English
"""
language = "en"
language = DEFAULT_FALLBACK_LANG
try:
language = request.environ["CKAN_LANG"]
except (TypeError, KeyError):
Expand Down

0 comments on commit 3d7a03d

Please sign in to comment.