Skip to content
Myr

inline_gettext_extension.py

This file

Path

docs/examples/inline_gettext_extension.py

73 lines · 2.4 KiB · Python

Last changed by

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

History of this file

Take it

1# -*- coding: utf-8 -*-2import re34from jinja2.exceptions import TemplateSyntaxError5from jinja2.ext import Extension6from jinja2.lexer import count_newlines7from jinja2.lexer import Token8910_outside_re = re.compile(r"\\?(gettext|_)\(")11_inside_re = re.compile(r"\\?[()]")121314class InlineGettext(Extension):15    """This extension implements support for inline gettext blocks::1617        <h1>_(Welcome)</h1>18        <p>_(This is a paragraph)</p>1920    Requires the i18n extension to be loaded and configured.21    """2223    def filter_stream(self, stream):24        paren_stack = 02526        for token in stream:27            if token.type != "data":28                yield token29                continue3031            pos = 032            lineno = token.lineno3334            while 1:35                if not paren_stack:36                    match = _outside_re.search(token.value, pos)37                else:38                    match = _inside_re.search(token.value, pos)39                if match is None:40                    break41                new_pos = match.start()42                if new_pos > pos:43                    preval = token.value[pos:new_pos]44                    yield Token(lineno, "data", preval)45                    lineno += count_newlines(preval)46                gtok = match.group()47                if gtok[0] == "\\":48                    yield Token(lineno, "data", gtok[1:])49                elif not paren_stack:50                    yield Token(lineno, "block_begin", None)51                    yield Token(lineno, "name", "trans")52                    yield Token(lineno, "block_end", None)53                    paren_stack = 154                else:55                    if gtok == "(" or paren_stack > 1:56                        yield Token(lineno, "data", gtok)57                    paren_stack += gtok == ")" and -1 or 158                    if not paren_stack:59                        yield Token(lineno, "block_begin", None)60                        yield Token(lineno, "name", "endtrans")61                        yield Token(lineno, "block_end", None)62                pos = match.end()6364            if pos < len(token.value):65                yield Token(lineno, "data", token.value[pos:])6667        if paren_stack:68            raise TemplateSyntaxError(69                "unclosed gettext expression",70                token.lineno,71                stream.name,72                stream.filename,73            )