Skip to content
Myr

inline_gettext_extension.py

This file

Path

docs/examples/inline_gettext_extension.py

71 lines · 2.3 KiB · Python

Last changed by

Merge branch '3.1.x'David Lordbefore adoptionde61312

History of this file

Take it

1import re23from jinja2.exceptions import TemplateSyntaxError4from jinja2.ext import Extension5from jinja2.lexer import count_newlines6from jinja2.lexer import Token78_outside_re = re.compile(r"\\?(gettext|_)\(")9_inside_re = re.compile(r"\\?[()]")101112class InlineGettext(Extension):13    """This extension implements support for inline gettext blocks::1415        <h1>_(Welcome)</h1>16        <p>_(This is a paragraph)</p>1718    Requires the i18n extension to be loaded and configured.19    """2021    def filter_stream(self, stream):22        paren_stack = 02324        for token in stream:25            if token.type != "data":26                yield token27                continue2829            pos = 030            lineno = token.lineno3132            while True:33                if not paren_stack:34                    match = _outside_re.search(token.value, pos)35                else:36                    match = _inside_re.search(token.value, pos)37                if match is None:38                    break39                new_pos = match.start()40                if new_pos > pos:41                    preval = token.value[pos:new_pos]42                    yield Token(lineno, "data", preval)43                    lineno += count_newlines(preval)44                gtok = match.group()45                if gtok[0] == "\\":46                    yield Token(lineno, "data", gtok[1:])47                elif not paren_stack:48                    yield Token(lineno, "block_begin", None)49                    yield Token(lineno, "name", "trans")50                    yield Token(lineno, "block_end", None)51                    paren_stack = 152                else:53                    if gtok == "(" or paren_stack > 1:54                        yield Token(lineno, "data", gtok)55                    paren_stack += -1 if gtok == ")" else 156                    if not paren_stack:57                        yield Token(lineno, "block_begin", None)58                        yield Token(lineno, "name", "endtrans")59                        yield Token(lineno, "block_end", None)60                pos = match.end()6162            if pos < len(token.value):63                yield Token(lineno, "data", token.value[pos:])6465        if paren_stack:66            raise TemplateSyntaxError(67                "unclosed gettext expression",68                token.lineno,69                stream.name,70                stream.filename,71            )