| 1 |
import re |
| 2 |
|
| 3 |
from jinja2.exceptions import TemplateSyntaxError |
| 4 |
from jinja2.ext import Extension |
| 5 |
from jinja2.lexer import count_newlines |
| 6 |
from jinja2.lexer import Token |
| 7 |
|
| 8 |
_outside_re = re.compile(r"\\?(gettext|_)\(") |
| 9 |
_inside_re = re.compile(r"\\?[()]") |
| 10 |
|
| 11 |
|
| 12 |
class InlineGettext(Extension): |
| 13 |
"""This extension implements support for inline gettext blocks:: |
| 14 |
|
| 15 |
<h1>_(Welcome)</h1> |
| 16 |
<p>_(This is a paragraph)</p> |
| 17 |
|
| 18 |
Requires the i18n extension to be loaded and configured. |
| 19 |
""" |
| 20 |
|
| 21 |
def filter_stream(self, stream): |
| 22 |
paren_stack = 0 |
| 23 |
|
| 24 |
for token in stream: |
| 25 |
if token.type != "data": |
| 26 |
yield token |
| 27 |
continue |
| 28 |
|
| 29 |
pos = 0 |
| 30 |
lineno = token.lineno |
| 31 |
|
| 32 |
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 |
break |
| 39 |
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 = 1 |
| 52 |
else: |
| 53 |
if gtok == "(" or paren_stack > 1: |
| 54 |
yield Token(lineno, "data", gtok) |
| 55 |
paren_stack += -1 if gtok == ")" else 1 |
| 56 |
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() |
| 61 |
|
| 62 |
if pos < len(token.value): |
| 63 |
yield Token(lineno, "data", token.value[pos:]) |
| 64 |
|
| 65 |
if paren_stack: |
| 66 |
raise TemplateSyntaxError( |
| 67 |
"unclosed gettext expression", |
| 68 |
token.lineno, |
| 69 |
stream.name, |
| 70 |
stream.filename, |
| 71 |
) |