inline_gettext_extension.py
This file
Path
docs/examples/inline_gettext_extension.py
72 lines · 2.3 KiB · Python
Last changed by
Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
History of this fileTake it
The walk stopped after 200 commits: lines older than 9ff27f6 point at it.
add python 3.8 classifier, clean up changelogDavid Lordbefore adoption9ff27f6
lines 1–32why, one step back1import re23from jinja2.exceptions import TemplateSyntaxError4from jinja2.ext import Extension5from jinja2.lexer import count_newlines6from jinja2.lexer import Token789_outside_re = re.compile(r"\\?(gettext|_)\(")10_inside_re = re.compile(r"\\?[()]")111213class InlineGettext(Extension):14 """This extension implements support for inline gettext blocks::1516 <h1>_(Welcome)</h1>17 <p>_(This is a paragraph)</p>1819 Requires the i18n extension to be loaded and configured.20 """2122 def filter_stream(self, stream):23 paren_stack = 02425 for token in stream:26 if token.type != "data":27 yield token28 continue2930 pos = 031 lineno = token.lineno32Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 33why, one step back33 while True:add python 3.8 classifier, clean up changelogDavid Lordbefore adoption9ff27f6
lines 34–55why, one step back34 if not paren_stack:35 match = _outside_re.search(token.value, pos)36 else:37 match = _inside_re.search(token.value, pos)38 if match is None:39 break40 new_pos = match.start()41 if new_pos > pos:42 preval = token.value[pos:new_pos]43 yield Token(lineno, "data", preval)44 lineno += count_newlines(preval)45 gtok = match.group()46 if gtok[0] == "\\":47 yield Token(lineno, "data", gtok[1:])48 elif not paren_stack:49 yield Token(lineno, "block_begin", None)50 yield Token(lineno, "name", "trans")51 yield Token(lineno, "block_end", None)52 paren_stack = 153 else:54 if gtok == "(" or paren_stack > 1:55 yield Token(lineno, "data", gtok)Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 56why, one step back56 paren_stack += -1 if gtok == ")" else 1add python 3.8 classifier, clean up changelogDavid Lordbefore adoption9ff27f6
lines 57–72why, one step back57 if not paren_stack:58 yield Token(lineno, "block_begin", None)59 yield Token(lineno, "name", "endtrans")60 yield Token(lineno, "block_end", None)61 pos = match.end()6263 if pos < len(token.value):64 yield Token(lineno, "data", token.value[pos:])6566 if paren_stack:67 raise TemplateSyntaxError(68 "unclosed gettext expression",69 token.lineno,70 stream.name,71 stream.filename,72 )