Skip to content
Myr

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

5 files+100 added−8 removed

modified:docs/extensions.rst+5 added
227 unmodified lines
228 .. attribute:: value229230 The value of the token.231232There is also a utility function in the lexer module that can count newline233characters in strings:234235.. autofunction:: jinja2.lexer.count_newlines236237AST238~~~239240The AST (Abstract Syntax Tree) is used to represent a template after parsing.
14 unmodified lines
added:ext/inlinegettext.py+78 added
1# -*- 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.89 :copyright: Copyright 2008 by Armin Ronacher.10 :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)
modified:jinja2/ext.py+6 added-1 removed
14 unmodified lines
15from jinja2.defaults import *16from jinja2.environment import get_spontaneous_environment17from jinja2.runtime import Undefined, concat18from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError19from jinja2.lexer import Token19from jinja2.utils import contextfunction, import_string, Markup202122# the only real useful gettext functions for a Jinja template. Note
55 unmodified lines
78 """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`.8283 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 stream8889 def parse(self, parser):
173 unmodified lines
263 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'271272 return referenced, concat(buf)
132 unmodified lines
modified:jinja2/lexer.py+7 added
69 unmodified lines
70operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in71 sorted(operators, key=lambda x: -len(x))))727374def 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))798081class Failure(object):82 """Class that raises a `TemplateSyntaxError` if called.83 Used by the `Lexer` to specify known errors.84 """
479 unmodified lines
modified:tests/test_ext.py+4 added-7 removed
6 unmodified lines
7 :license: BSD, see LICENSE for more details.8"""9import re10from jinja2 import Environment, nodes11from jinja2.ext import Extension, Token11from jinja2.ext import Extension12from jinja2.lexer import Token, count_newlines131415importable_object = 23161717_line_re = re.compile(r'(\r\n|\r|\n)')18_gettext_re = re.compile(r'_\((([^)\\]*(?:\\.[^)\\]*)*))\)(?s)')18_gettext_re = re.compile(r'_\((.*?)\)')192021class TestExtension(Extension):22 tags = set(['test'])
31 unmodified lines
54 yield t55 else:56 yield token5758 def count_lines(self, value):59 return len(_line_re.findall(value))6058 def interpolate(self, token):59 pos = 060 end = len(token.value)61 lineno = token.lineno
3 unmodified lines
65 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