Added example extension that uses the stream filtering and added unittests.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 3e3a9be · Browse files · 5 files·+100 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+100 added−8 removed
- tests:+4 added−7 removed
- other:+96 added−1 removed
Provenance
- Commit
d02fc7d- Tree
65ebb6b- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
3e3a9be
5 files changed+100 added−8 removed
modified:docs/extensions.rst+5 added
227 unmodified lines228 .. attribute:: value229 230 The value of the token.231 232+There is also a utility function in the lexer module that can count newline233+characters in strings:234+235+.. autofunction:: jinja2.lexer.count_newlines236+237 AST238 ~~~239 240 The AST (Abstract Syntax Tree) is used to represent a template after parsing.14 unmodified linesadded:ext/inlinegettext.py+78 added
1+# -*- coding: utf-8 -*-2+"""3+ Inline Gettext4+ ~~~~~~~~~~~~~~5+6+ An example extension for Jinja2 that supports inline gettext calls.7+ Requires the i18n extension to be loaded.8+9+ :copyright: Copyright 2008 by Armin Ronacher.10+ :license: BSD.11+"""12+import re13+from jinja2.ext import Extension14+from jinja2.lexer import Token, count_newlines15+from jinja2.exceptions import TemplateSyntaxError16+17+18+_outside_re = re.compile(r'\\?(gettext|_)\(')19+_inside_re = re.compile(r'\\?[()]')20+21+22+class InlineGettext(Extension):23+ """This extension implements support for inline gettext blocks::24+25+ <h1>_(Welcome)</h1>26+ <p>_(This is a paragraph)</p>27+28+ Requires the i18n extension to be loaded and configured.29+ """30+31+ def filter_stream(self, stream):32+ paren_stack = 033+34+ for token in stream:35+ if token.type is not 'data':36+ yield token37+ continue38+39+ pos = 040+ lineno = token.lineno41+42+ 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()71+72+ if pos < len(token.value):73+ yield Token(lineno, 'data', token.value[pos:])74+75+ if paren_stack:76+ raise TemplateSyntaxError('unclosed gettext expression',77+ token.lineno, stream.name,78+ stream.filename)modified:jinja2/ext.py+6 added-1 removed
14 unmodified lines15 from jinja2.defaults import *16 from jinja2.environment import get_spontaneous_environment17 from jinja2.runtime import Undefined, concat18 from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError19-from jinja2.lexer import Token19 from jinja2.utils import contextfunction, import_string, Markup20 21 22 # the only real useful gettext functions for a Jinja template. Note55 unmodified lines78 """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used79 to filter tokens returned. This method has to return an iterable of80 :class:`~jinja2.lexer.Token`\s, but it doesn't have to return a81 :class:`~jinja2.lexer.TokenStream`.82+83+ In the `ext` folder of the Jinja2 source distribution there is a file84+ called `inlinegettext.py` which implements a filter that utilizes this85+ method.86 """87 return stream88 89 def parse(self, parser):173 unmodified lines263 parser.fail('a translatable section can have only one '264 'pluralize section')265 parser.fail('control structures in translatable sections are '266 'not allowed')267+ elif parser.stream.eos:268+ parser.fail('unclosed translation block')269 else:270 assert False, 'internal parser error'271 272 return referenced, concat(buf)132 unmodified linesmodified:jinja2/lexer.py+7 added
69 unmodified lines70 operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in71 sorted(operators, key=lambda x: -len(x))))72 73 74+def count_newlines(value):75+ """Count the number of newline characters in the string. This is76+ useful for extensions that filter a stream.77+ """78+ return len(newline_re.findall(value))79+80+81 class Failure(object):82 """Class that raises a `TemplateSyntaxError` if called.83 Used by the `Lexer` to specify known errors.84 """479 unmodified linesmodified:tests/test_ext.py+4 added-7 removed
6 unmodified lines7 :license: BSD, see LICENSE for more details.8 """9 import re10 from jinja2 import Environment, nodes11-from jinja2.ext import Extension, Token11+from jinja2.ext import Extension12+from jinja2.lexer import Token, count_newlines13 14 15 importable_object = 2316 17 17-_line_re = re.compile(r'(\r\n|\r|\n)')18-_gettext_re = re.compile(r'_\((([^)\\]*(?:\\.[^)\\]*)*))\)(?s)')18+_gettext_re = re.compile(r'_\((.*?)\)')19 20 21 class TestExtension(Extension):22 tags = set(['test'])31 unmodified lines54 yield t55 else:56 yield token57 58- def count_lines(self, value):59- return len(_line_re.findall(value))60-58 def interpolate(self, token):59 pos = 060 end = len(token.value)61 lineno = token.lineno3 unmodified lines65 break66 value = token.value[pos:match.start()]67 if value:68 yield Token(lineno, 'data', value)72- lineno += self.count_lines(token.value)69+ lineno += count_newlines(token.value)70 yield Token(lineno, 'variable_begin', None)71 yield Token(lineno, 'name', 'gettext')72 yield Token(lineno, 'lparen', None)73 yield Token(lineno, 'string', match.group(1))64 unmodified lines