From 0a1abb5e45bd1d41119c928e14a402b7d181bcd0 Mon Sep 17 00:00:00 2001 From: Martin Trigaux Date: Fri, 20 Oct 2023 12:23:45 +0200 Subject: [PATCH] [IMP] tools: allow to use Markup and gettext Before this commit escape was needed to use a Markup object as a parameter, hence loosing the fallback mechanism in translations >>> escape(_("Order %s has been confirmed")) % Markup("%s") % order.name Markup("Order SO42 has been confirmed") Now it is possible to explictly give a Markup object to the gettext call >>> _("Order %s has been confirmed", Markup("%s") % order.name) Markup("Order SO42 has been confirmed") Part-of: odoo/odoo#139316 --- .../test_translation_import/tests/test_term_count.py | 8 ++++++++ odoo/tools/translate.py | 3 +++ 2 files changed, 11 insertions(+) diff --git a/odoo/addons/test_translation_import/tests/test_term_count.py b/odoo/addons/test_translation_import/tests/test_term_count.py index 41b66bb490b..e608f534cac 100644 --- a/odoo/addons/test_translation_import/tests/test_term_count.py +++ b/odoo/addons/test_translation_import/tests/test_term_count.py @@ -2,6 +2,7 @@ import base64 import io +from markupsafe import Markup from odoo.tests import common, tagged from odoo.tools.misc import file_open, mute_logger @@ -219,6 +220,13 @@ class TestImport(common.TransactionCase): with self.assertRaises(KeyError): model_fr_BE.get_code_named_placeholder_translation(symbol="🧀"), + # correctly translate markup + self.assertEqual( + model_fr_BE.get_code_named_placeholder_translation(num=Markup(2), symbol="<🧀>"), + Markup("Code, 2, <🧀>, Français, Belgium"), + "Translation placeholders were not applied when using Markup" + ) + @tagged('post_install', '-at_install') class TestTranslationFlow(common.TransactionCase): diff --git a/odoo/tools/translate.py b/odoo/tools/translate.py index 5b3fc6e9a39..b711657731a 100644 --- a/odoo/tools/translate.py +++ b/odoo/tools/translate.py @@ -24,6 +24,7 @@ from os.path import join from pathlib import Path from babel.messages import extract from lxml import etree, html +from markupsafe import escape, Markup from psycopg2.extras import Json import odoo @@ -460,6 +461,8 @@ class GettextAlias(object): translation = self._get_translation(source) assert not (args and kwargs) if args or kwargs: + if any(isinstance(a, Markup) for a in itertools.chain(args, kwargs.values())): + translation = escape(translation) try: return translation % (args or kwargs) except (TypeError, ValueError, KeyError):