inlinegettext.py
This file
Path
ext/inlinegettext.py
78 lines · 2.6 KiB · Python
Last changed by
Copyright switch to "The Jinja Team".Armin Ronacherbefore adoption62ccd1b
History of this fileTake it
Added example extension that uses the stream filtering and added unittests.Armin Ronacherbefore adoptiond02fc7d
lines 1–8why, one step back1# -*- coding: utf-8 -*-2"""3 Inline Gettext4 ~~~~~~~~~~~~~~56 An example extension for Jinja2 that supports inline gettext calls.7 Requires the i18n extension to be loaded.8Copyright switch to "The Jinja Team".Armin Ronacherbefore adoption62ccd1b
line 9why, one step back9 :copyright: (c) 2009 by the Jinja Team.Added example extension that uses the stream filtering and added unittests.Armin Ronacherbefore adoptiond02fc7d
lines 10–78why, one step back10 :license: BSD.11"""12import re13from jinja2.ext import Extension14from jinja2.lexer import Token, count_newlines15from jinja2.exceptions import TemplateSyntaxError161718_outside_re = re.compile(r'\\?(gettext|_)\(')19_inside_re = re.compile(r'\\?[()]')202122class InlineGettext(Extension):23 """This extension implements support for inline gettext blocks::2425 <h1>_(Welcome)</h1>26 <p>_(This is a paragraph)</p>2728 Requires the i18n extension to be loaded and configured.29 """3031 def filter_stream(self, stream):32 paren_stack = 03334 for token in stream:35 if token.type is not 'data':36 yield token37 continue3839 pos = 040 lineno = token.lineno4142 while 1:43 if not paren_stack:44 match = _outside_re.search(token.value, pos)45 else:46 match = _inside_re.search(token.value, pos)47 if match is None:48 break49 new_pos = match.start()50 if new_pos > pos:51 preval = token.value[pos:new_pos]52 yield Token(lineno, 'data', preval)53 lineno += count_newlines(preval)54 gtok = match.group()55 if gtok[0] == '\\':56 yield Token(lineno, 'data', gtok[1:])57 elif not paren_stack:58 yield Token(lineno, 'block_begin', None)59 yield Token(lineno, 'name', 'trans')60 yield Token(lineno, 'block_end', None)61 paren_stack = 162 else:63 if gtok == '(' or paren_stack > 1:64 yield Token(lineno, 'data', gtok)65 paren_stack += gtok == ')' and -1 or 166 if not paren_stack:67 yield Token(lineno, 'block_begin', None)68 yield Token(lineno, 'name', 'endtrans')69 yield Token(lineno, 'block_end', None)70 pos = match.end()7172 if pos < len(token.value):73 yield Token(lineno, 'data', token.value[pos:])7475 if paren_stack:76 raise TemplateSyntaxError('unclosed gettext expression',77 token.lineno, stream.name,78 stream.filename)