Skip to content

Commit

Permalink
Fix translation of templates with extensions tags (#8)
Browse files Browse the repository at this point in the history
When trying to translate templates that use tags from extensions different than jinja2.ext.i18n.
At the moment of exporting the literals of those templates the jinja2 engine does not recognize the tags and throws an exception.

This can be reproduced using the "do" statement in a template and trying to define tryton translations.
https://jinja.palletsprojects.com/en/3.1.x/templates/#expression-statement

Co-authored-by: Victor <[email protected]>
  • Loading branch information
2 people authored and GuillemCalidae committed Jul 27, 2022
1 parent cd4fa09 commit 52a1528
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions report.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@
from trytond.report.report import TranslateFactory


class JinjaExtensionsMixin():
JINJA_EXTENSIONS = [
'jinja2.ext.i18n',
'jinja2.ext.do',
'jinja2.ext.loopcontrols',
]

@classmethod
def get_extensions(cls):
return cls.JINJA_EXTENSIONS


class JinjaTranslator(object):

def __init__(self, method):
Expand All @@ -20,13 +32,7 @@ def __init__(self, method):
self.ungettext = method


class Jinja2Report(metaclass=PoolMeta):

JINJA_EXTENSIONS = [
'jinja2.ext.i18n',
'jinja2.ext.do',
'jinja2.ext.loopcontrols',
]
class Jinja2Report(JinjaExtensionsMixin, metaclass=PoolMeta):

@classmethod
def render(cls, action, context):
Expand All @@ -36,7 +42,7 @@ def render(cls, action, context):

@classmethod
def get_environ(cls):
env = jinja2.Environment(extensions=cls.JINJA_EXTENSIONS)
env = jinja2.Environment(extensions=cls.get_extensions())
translations = cls.get_translations()
env.install_gettext_translations(translations)
env.filters['b64encode'] = b64encode
Expand Down Expand Up @@ -72,7 +78,7 @@ def get_attachment(cls, record, name):
return data


class SetTranslationJinja2(metaclass=PoolMeta):
class SetTranslationJinja2(JinjaExtensionsMixin, metaclass=PoolMeta):

__name__ = 'ir.translation.set'

Expand All @@ -84,7 +90,7 @@ def extract_report_html(self, content):
# content with the picky genshi translation extractor,
# the set-translations process will fail in presence of
# reports tailored for other template languages like jinja2.
env = jinja2.Environment(extensions=['jinja2.ext.i18n'])
env = jinja2.Environment(extensions=self.get_extensions())
for _, _, str_ in env.extract_translations(content.decode()):
if str_:
yield str_
Expand Down

0 comments on commit 52a1528

Please sign in to comment.