moved trans extension from jinja2.i18n to jinja2.ext and fixed some more 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 203bfcb · Browse files · 11 files·+332 added−424 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+332 added−424 removed
- tests:+11 added−40 removed
- other:+321 added−384 removed
Provenance
- Commit
b5124e6- Tree
ad199fc- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
203bfcb
11 files changed+332 added−424 removed
modified:jinja2/environment.py+27 added-26 removed
21 unmodified lines22 # for direct template usage we have up to ten living environments23 _spontaneous_environments = LRUCache(10)24 25 26-def _get_spontaneous_environment(*args):26+def get_spontaneous_environment(*args):27 """Return a new spontaneus environment. A spontaneus environment is an28 unnamed and unaccessable (in theory) environment that is used for29 template generated from a string and not from the file system.30 """53 unmodified lines84 comment_start_string='{#',85 comment_end_string='#}',86 line_statement_prefix=None,87 trim_blocks=False,88+ extensions=(),89 optimized=True,90 undefined=Undefined,90- loader=None,91- extensions=(),92- finalize=unicode):91+ finalize=unicode,92+ loader=None):93+ # !!Important notice!!94+ # The constructor accepts quite a few arguments that should be95+ # passed by keyword rather than position. However it's important to96+ # not change the order of arguments because it's used at least97+ # internally in those cases:98+ # - spontaneus environments (i18n extension and Template)99+ # - unittests100+ # If parameter changes are required only add parameters at the end101+ # and don't change the arguments (or the defaults!) of the arguments102+ # up to (but excluding) loader.103 """Here the possible initialization parameters:104 105 ========================= ============================================106 `block_start_string` the string marking the begin of a block.11 unmodified lines118 documentation for more details.119 `trim_blocks` If this is set to ``True`` the first newline120 after a block is removed (block, not121 variable tag!). Defaults to ``False``.122+ `extensions` List of Jinja extensions to use.123 `optimized` should the optimizer be enabled? Default is124 ``True``.125 `undefined` a subclass of `Undefined` that is used to126 represent undefined variables.116- `loader` the loader which should be used.117- `extensions` List of Jinja extensions to use.127 `finalize` A callable that finalizes the variable. Per128 default this is `unicode`, other useful129 builtin finalizers are `escape`.130+ `loader` the loader which should be used.131 ========================= ============================================132 """133 134 # santity checks12 unmodified lines147 self.comment_end_string = comment_end_string148 self.line_statement_prefix = line_statement_prefix149 self.trim_blocks = trim_blocks150 141- # load extensions142- self.extensions = []143- for extension in extensions:144- if isinstance(extension, basestring):145- extension = import_string(extension)146- # extensions are instanciated early but initalized later.147- self.extensions.append(object.__new__(extension))148-151 # runtime information152 self.undefined = undefined153 self.optimized = optimized154 self.finalize = finalize8 unmodified lines163 164 # create lexer165 self.lexer = Lexer(self)166 165- # initialize extensions166- for extension in self.extensions:167- extension.__init__(self)167+ # load extensions168+ self.extensions = []169+ for extension in extensions:170+ if isinstance(extension, basestring):171+ extension = import_string(extension)172+ self.extensions.append(extension(self))173 174 def subscribe(self, obj, argument):175 """Get an item or attribute of an object."""176 try:109 unmodified lines286 comment_start_string='{#',287 comment_end_string='#}',288 line_statement_prefix=None,289 trim_blocks=False,290+ extensions=(),291 optimized=True,292 undefined=Undefined,287- extensions=(),293 finalize=unicode):289- # make sure extensions are hashable290- extensions = tuple(extensions)291- env = _get_spontaneous_environment(294+ env = get_spontaneous_environment(295 block_start_string, block_end_string, variable_start_string,296 variable_end_string, comment_start_string, comment_end_string,294- line_statement_prefix, trim_blocks, optimized, undefined,295- None, extensions, finalize)297+ line_statement_prefix, trim_blocks, tuple(extensions), optimized,298+ undefined, finalize)299 return env.from_string(source, template_class=cls)300 301 def render(self, *args, **kwargs):302 """Render the template into a string."""101 unmodified lines404 next = self._gen.next405 406 while 1:407 try:405- while 1:408+ while c_size < size:409 push(next())410 c_size += 1408- if c_size >= size:409- raise StopIteration()411 except StopIteration:412 if not c_size:413 raise414 yield u''.join(buf)16 unmodified linesmodified:jinja2/ext.py+247 added-6 removed
1 unmodified line2 """3 jinja2.ext4 ~~~~~~~~~~5 6- Jinja extensions (EXPERIMENAL)6+ Jinja extensions allow to add custom tags similar to the way django custom7+ tags work. By default two example extensions exist: an i18n and a cache8+ extension.9 8- The plan: i18n and caching becomes a parser extension. cache/endcache9- as well as trans/endtrans are not keyword and don't have nodes but10- translate into regular jinja nodes so that the person who writes such11- custom tags doesn't have to generate python code himself.12-10 :copyright: Copyright 2008 by Armin Ronacher.11 :license: BSD.12 """13+from collections import deque14 from jinja2 import nodes15+from jinja2.environment import get_spontaneous_environment16+from jinja2.runtime import Undefined17+from jinja2.parser import statement_end_tokens18+from jinja2.exceptions import TemplateAssertionError19+from jinja2.utils import import_string20 21 22+# the only real useful gettext functions for a Jinja template. Note23+# that ugettext must be assigned to gettext as Jinja doesn't support24+# non unicode strings.25+GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')26+27+28 class Extension(object):29 """Instances of this class store parser extensions."""30 31 #: if this extension parses this is the list of tags it's listening to.27 unmodified lines59 return nodes.CallBlock(60 nodes.Call(nodes.Name('cache_support', 'load'), args, [], None, None),61 [], [], body62 )63+64+65+class TransExtension(Extension):66+ """This extension adds gettext support to Jinja."""67+ tags = set(['trans'])68+69+ def __init__(self, environment):70+ Extension.__init__(self, environment)71+ environment.globals.update({72+ '_': lambda x: x,73+ 'gettext': lambda x: x,74+ 'ngettext': lambda s, p, n: (s, p)[n != 1]75+ })76+77+ def parse(self, parser):78+ """Parse a translatable tag."""79+ lineno = parser.stream.next().lineno80+81+ # skip colon for python compatibility82+ if parser.stream.current.type is 'colon':83+ parser.stream.next()84+85+ # find all the variables referenced. Additionally a variable can be86+ # defined in the body of the trans block too, but this is checked at87+ # a later state.88+ plural_expr = None89+ variables = {}90+ while parser.stream.current.type is not 'block_end':91+ if variables:92+ parser.stream.expect('comma')93+ name = parser.stream.expect('name')94+ if name.value in variables:95+ raise TemplateAssertionError('translatable variable %r defined '96+ 'twice.' % name.value, name.lineno,97+ parser.filename)98+99+ # expressions100+ if parser.stream.current.type is 'assign':101+ parser.stream.next()102+ variables[name.value] = var = parser.parse_expression()103+ else:104+ variables[name.value] = var = nodes.Name(name.value, 'load')105+ if plural_expr is None:106+ plural_expr = var107+ parser.stream.expect('block_end')108+109+ plural = plural_names = None110+ have_plural = False111+ referenced = set()112+113+ # now parse until endtrans or pluralize114+ singular_names, singular = self._parse_block(parser, True)115+ if singular_names:116+ referenced.update(singular_names)117+ if plural_expr is None:118+ plural_expr = nodes.Name(singular_names[0], 'load')119+120+ # if we have a pluralize block, we parse that too121+ if parser.stream.current.test('name:pluralize'):122+ have_plural = True123+ parser.stream.next()124+ if parser.stream.current.type is not 'block_end':125+ plural_expr = parser.parse_expression()126+ parser.stream.expect('block_end')127+ plural_names, plural = self._parse_block(parser, False)128+ parser.stream.next()129+ referenced.update(plural_names)130+ else:131+ parser.stream.next()132+133+ # register free names as simple name expressions134+ for var in referenced:135+ if var not in variables:136+ variables[var] = nodes.Name(var, 'load')137+138+ # no variables referenced? no need to escape139+ if not referenced:140+ singular = singular.replace('%%', '%')141+ if plural:142+ plural = plural.replace('%%', '%')143+144+ if not have_plural:145+ plural_expr = None146+ elif plural_expr is None:147+ raise TemplateAssertionError('pluralize without variables',148+ lineno, parser.filename)149+150+ if variables:151+ variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)152+ for x, y in variables.items()])153+ else:154+ variables = None155+156+ node = self._make_node(singular, plural, variables, plural_expr)157+ node.set_lineno(lineno)158+ return node159+160+ def _parse_block(self, parser, allow_pluralize):161+ """Parse until the next block tag with a given name."""162+ referenced = []163+ buf = []164+ while 1:165+ if parser.stream.current.type is 'data':166+ buf.append(parser.stream.current.value.replace('%', '%%'))167+ parser.stream.next()168+ elif parser.stream.current.type is 'variable_begin':169+ parser.stream.next()170+ name = parser.stream.expect('name').value171+ referenced.append(name)172+ buf.append('%%(%s)s' % name)173+ parser.stream.expect('variable_end')174+ elif parser.stream.current.type is 'block_begin':175+ parser.stream.next()176+ if parser.stream.current.test('name:endtrans'):177+ break178+ elif parser.stream.current.test('name:pluralize'):179+ if allow_pluralize:180+ break181+ raise TemplateSyntaxError('a translatable section can '182+ 'have only one pluralize '183+ 'section',184+ parser.stream.current.lineno,185+ parser.filename)186+ raise TemplateSyntaxError('control structures in translatable'187+ ' sections are not allowed.',188+ parser.stream.current.lineno,189+ parser.filename)190+ else:191+ assert False, 'internal parser error'192+193+ return referenced, u''.join(buf)194+195+ def _make_node(self, singular, plural, variables, plural_expr):196+ """Generates a useful node from the data provided."""197+ # singular only:198+ if plural_expr is None:199+ gettext = nodes.Name('gettext', 'load')200+ node = nodes.Call(gettext, [nodes.Const(singular)],201+ [], None, None)202+ if variables:203+ node = nodes.Mod(node, variables)204+205+ # singular and plural206+ else:207+ ngettext = nodes.Name('ngettext', 'load')208+ node = nodes.Call(ngettext, [209+ nodes.Const(singular),210+ nodes.Const(plural),211+ plural_expr212+ ], [], None, None)213+ if variables:214+ node = nodes.Mod(node, variables)215+ return nodes.Output([node])216+217+218+def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS):219+ """Extract localizable strings from the given template node.220+221+ For every string found this function yields a ``(lineno, function,222+ message)`` tuple, where:223+224+ * ``lineno`` is the number of the line on which the string was found,225+ * ``function`` is the name of the ``gettext`` function used (if the226+ string was extracted from embedded Python code), and227+ * ``message`` is the string itself (a ``unicode`` object, or a tuple228+ of ``unicode`` objects for functions with multiple string arguments).229+ """230+ for node in node.find_all(nodes.Call):231+ if not isinstance(node.node, nodes.Name) or \232+ node.node.name not in gettext_functions:233+ continue234+235+ strings = []236+ for arg in node.args:237+ if isinstance(arg, nodes.Const) and \238+ isinstance(arg.value, basestring):239+ strings.append(arg.value)240+ else:241+ strings.append(None)242+243+ if len(strings) == 1:244+ strings = strings[0]245+ else:246+ strings = tuple(strings)247+ yield node.lineno, node.node.name, strings248+249+250+def babel_extract(fileobj, keywords, comment_tags, options):251+ """Babel extraction method for Jinja templates.252+253+ :param fileobj: the file-like object the messages should be extracted from254+ :param keywords: a list of keywords (i.e. function names) that should be255+ recognized as translation functions256+ :param comment_tags: a list of translator tags to search for and include257+ in the results. (Unused)258+ :param options: a dictionary of additional options (optional)259+ :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.260+ (comments will be empty currently)261+ """262+ encoding = options.get('encoding', 'utf-8')263+264+ have_trans_extension = False265+ extensions = []266+ for extension in options.get('extensions', '').split(','):267+ extension = extension.strip()268+ if not extension:269+ continue270+ extension = import_string(extension)271+ if extension is TransExtension:272+ have_trans_extension = True273+ extensions.append(extension)274+ if not have_trans_extension:275+ extensions.append(TransExtension)276+277+ environment = get_spontaneous_environment(278+ options.get('block_start_string', '{%'),279+ options.get('block_end_string', '%}'),280+ options.get('variable_start_string', '{{'),281+ options.get('variable_end_string', '}}'),282+ options.get('comment_start_string', '{#'),283+ options.get('comment_end_string', '#}'),284+ options.get('line_statement_prefix') or None,285+ options.get('trim_blocks', '').lower() in ('1', 'on', 'yes', 'true'),286+ tuple(extensions),287+ # fill with defaults so that environments are shared288+ # with other spontaneus environments.289+ True, Undefined, unicode290+ )291+292+ node = environment.parse(fileobj.read().decode(encoding))293+ for lineno, func, message in extract_from_ast(node, keywords):294+ yield lineno, func, message, []deleted:jinja2/i18n.py-246 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.i18n4- ~~~~~~~~~~~5-6- i18n support for Jinja.7-8- :copyright: Copyright 2008 by Armin Ronacher.9- :license: BSD.10-"""11-from collections import deque12-from jinja2 import nodes13-from jinja2.environment import Environment14-from jinja2.parser import statement_end_tokens15-from jinja2.ext import Extension16-from jinja2.exceptions import TemplateAssertionError17-18-19-# the only real useful gettext functions for a Jinja template. Note20-# that ugettext must be assigned to gettext as Jinja doesn't support21-# non unicode strings.22-GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')23-24-25-def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS):26- """Extract localizable strings from the given template node.27-28- For every string found this function yields a ``(lineno, function,29- message)`` tuple, where:30-31- * ``lineno`` is the number of the line on which the string was found,32- * ``function`` is the name of the ``gettext`` function used (if the33- string was extracted from embedded Python code), and34- * ``message`` is the string itself (a ``unicode`` object, or a tuple35- of ``unicode`` objects for functions with multiple string arguments).36- """37- for node in node.find_all(nodes.Call):38- if not isinstance(node.node, nodes.Name) or \39- node.node.name not in gettext_functions:40- continue41-42- strings = []43- for arg in node.args:44- if isinstance(arg, nodes.Const) and \45- isinstance(arg.value, basestring):46- strings.append(arg.value)47- else:48- strings.append(None)49-50- if len(strings) == 1:51- strings = strings[0]52- else:53- strings = tuple(strings)54- yield node.lineno, node.node.name, strings55-56-57-def babel_extract(fileobj, keywords, comment_tags, options):58- """Babel extraction method for Jinja templates.59-60- :param fileobj: the file-like object the messages should be extracted from61- :param keywords: a list of keywords (i.e. function names) that should be62- recognized as translation functions63- :param comment_tags: a list of translator tags to search for and include64- in the results. (Unused)65- :param options: a dictionary of additional options (optional)66- :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.67- (comments will be empty currently)68- """69- encoding = options.get('encoding', 'utf-8')70- extensions = [x.strip() for x in options.get('extensions', '').split(',')]71- environment = Environment(72- options.get('block_start_string', '{%'),73- options.get('block_end_string', '%}'),74- options.get('variable_start_string', '{{'),75- options.get('variable_end_string', '}}'),76- options.get('comment_start_string', '{#'),77- options.get('comment_end_string', '#}'),78- options.get('line_statement_prefix') or None,79- options.get('trim_blocks', '').lower() in ('1', 'on', 'yes', 'true'),80- extensions=[x for x in extensions if x]81- )82-83- # add the i18n extension only if it's not yet in the list. Some people84- # might use a script to sync the babel ini with the Jinja configuration85- # so we want to avoid having the trans extension twice in the list.86- for extension in environment.extensions:87- if isinstance(extension, TransExtension):88- break89- else:90- environment.extensions.append(TransExtension(environment))91-92- node = environment.parse(fileobj.read().decode(encoding))93- for lineno, func, message in extract_from_ast(node, keywords):94- yield lineno, func, message, []95-96-97-class TransExtension(Extension):98- tags = set(['trans'])99-100- def __init__(self, environment):101- Extension.__init__(self, environment)102- environment.globals.update({103- '_': lambda x: x,104- 'gettext': lambda x: x,105- 'ngettext': lambda s, p, n: (s, p)[n != 1]106- })107-108- def parse(self, parser):109- """Parse a translatable tag."""110- lineno = parser.stream.next().lineno111-112- # skip colon for python compatibility113- if parser.stream.current.type is 'colon':114- parser.stream.next()115-116- # find all the variables referenced. Additionally a variable can be117- # defined in the body of the trans block too, but this is checked at118- # a later state.119- plural_expr = None120- variables = {}121- while parser.stream.current.type is not 'block_end':122- if variables:123- parser.stream.expect('comma')124- name = parser.stream.expect('name')125- if name.value in variables:126- raise TemplateAssertionError('translatable variable %r defined '127- 'twice.' % name.value, name.lineno,128- parser.filename)129-130- # expressions131- if parser.stream.current.type is 'assign':132- parser.stream.next()133- variables[name.value] = var = parser.parse_expression()134- else:135- variables[name.value] = var = nodes.Name(name.value, 'load')136- if plural_expr is None:137- plural_expr = var138- parser.stream.expect('block_end')139-140- plural = plural_names = None141- have_plural = False142- referenced = set()143-144- # now parse until endtrans or pluralize145- singular_names, singular = self._parse_block(parser, True)146- if singular_names:147- referenced.update(singular_names)148- if plural_expr is None:149- plural_expr = nodes.Name(singular_names[0], 'load')150-151- # if we have a pluralize block, we parse that too152- if parser.stream.current.test('name:pluralize'):153- have_plural = True154- parser.stream.next()155- if parser.stream.current.type is not 'block_end':156- plural_expr = parser.parse_expression()157- parser.stream.expect('block_end')158- plural_names, plural = self._parse_block(parser, False)159- parser.stream.next()160- referenced.update(plural_names)161- else:162- parser.stream.next()163-164- # register free names as simple name expressions165- for var in referenced:166- if var not in variables:167- variables[var] = nodes.Name(var, 'load')168-169- # no variables referenced? no need to escape170- if not referenced:171- singular = singular.replace('%%', '%')172- if plural:173- plural = plural.replace('%%', '%')174-175- if not have_plural:176- plural_expr = None177- elif plural_expr is None:178- raise TemplateAssertionError('pluralize without variables',179- lineno, parser.filename)180-181- if variables:182- variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)183- for x, y in variables.items()])184- else:185- variables = None186-187- node = self._make_node(singular, plural, variables, plural_expr)188- node.set_lineno(lineno)189- return node190-191- def _parse_block(self, parser, allow_pluralize):192- """Parse until the next block tag with a given name."""193- referenced = []194- buf = []195- while 1:196- if parser.stream.current.type is 'data':197- buf.append(parser.stream.current.value.replace('%', '%%'))198- parser.stream.next()199- elif parser.stream.current.type is 'variable_begin':200- parser.stream.next()201- name = parser.stream.expect('name').value202- referenced.append(name)203- buf.append('%%(%s)s' % name)204- parser.stream.expect('variable_end')205- elif parser.stream.current.type is 'block_begin':206- parser.stream.next()207- if parser.stream.current.test('name:endtrans'):208- break209- elif parser.stream.current.test('name:pluralize'):210- if allow_pluralize:211- break212- raise TemplateSyntaxError('a translatable section can '213- 'have only one pluralize '214- 'section',215- parser.stream.current.lineno,216- parser.filename)217- raise TemplateSyntaxError('control structures in translatable'218- ' sections are not allowed.',219- parser.stream.current.lineno,220- parser.filename)221- else:222- assert False, 'internal parser error'223-224- return referenced, u''.join(buf)225-226- def _make_node(self, singular, plural, variables, plural_expr):227- """Generates a useful node from the data provided."""228- # singular only:229- if plural_expr is None:230- gettext = nodes.Name('gettext', 'load')231- node = nodes.Call(gettext, [nodes.Const(singular)],232- [], None, None)233- if variables:234- node = nodes.Mod(node, variables)235-236- # singular and plural237- else:238- ngettext = nodes.Name('ngettext', 'load')239- node = nodes.Call(ngettext, [240- nodes.Const(singular),241- nodes.Const(plural),242- plural_expr243- ], [], None, None)244- if variables:245- node = nodes.Mod(node, variables)246- return nodes.Output([node])modified:jinja2/lexer.py+19 added-88 removed
16 unmodified lines17 import re18 import unicodedata19 from jinja2.datastructure import TokenStream, Token20 from jinja2.exceptions import TemplateSyntaxError21-from weakref import WeakValueDictionary21+from jinja2.utils import LRUCache22 23 24 # cache for the lexers. Exists in order to be able to have multiple25 # environments with the same lexer26-_lexer_cache = WeakValueDictionary()26+_lexer_cache = LRUCache(10)27 28-28 # static regular expressions29 whitespace_re = re.compile(r'\s+(?um)')30 string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"31 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')32 integer_re = re.compile(r'\d+')33 name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')34 float_re = re.compile(r'\d+\.\d+')35 37-36 # set of used keywords37 keywords = set(['and', 'block', 'elif', 'else', 'endblock', 'print',38 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',39 'extends', 'filter', 'for', 'if', 'in', 'include',53 unmodified lines93 }94 95 96 def unescape_string(lineno, filename, s):99- r"""100- Unescape a string. Supported escapes:97+ r"""Unescape a string. Supported escapes:98 \a, \n, \r\, \f, \v, \\, \", \', \099 100 \x00, \u0000, \U00000000, \N{...}104-105- Not supported are \101 because imho redundant.101 """107- result = []108- write = result.append109- chariter = iter(s)110- next_char = chariter.next111-112- # faster lookup113- sescapes = simple_escapes114- uescapes = unicode_escapes115-102 try:117- for char in chariter:118- if char == '\\':119- char = next_char()120- if char in sescapes:121- write(sescapes[char])122- elif char in uescapes:123- seq = [next_char() for x in xrange(uescapes[char])]124- try:125- write(unichr(int(''.join(seq), 16)))126- except ValueError:127- raise TemplateSyntaxError('invalid unicode codepoint',128- lineno, filename)129- elif char == 'N':130- if next_char() != '{':131- raise TemplateSyntaxError('no name for codepoint',132- lineno, filename)133- seq = []134- while 1:135- char = next_char()136- if char == '}':137- break138- seq.append(char)139- try:140- write(unicodedata.lookup(u''.join(seq)))141- except KeyError:142- raise TemplateSyntaxError('unknown character name',143- lineno, filename)144- else:145- write('\\' + char)146- else:147- write(char)148- except StopIteration:149- raise TemplateSyntaxError('invalid string escape', lineno, filename)150- return u''.join(result)103+ return s.encode('ascii', 'backslashreplace').decode('unicode-escape')104+ except UnicodeError, e:105+ msg = str(e).split(':')[-1].strip()106+ raise TemplateSyntaxError(msg, lineno, filename)107 108 153-def unescape_regex(s):154- """155- Unescape rules for regular expressions.156- """157- buffer = []158- write = buffer.append159- in_escape = False160- for char in s:161- if in_escape:162- in_escape = False163- if char not in safe_chars:164- write('\\' + char)165- continue166- write(char)167- return u''.join(buffer)168-169-109 class Failure(object):171- """172- Class that raises a `TemplateSyntaxError` if called.110+ """Class that raises a `TemplateSyntaxError` if called.111 Used by the `Lexer` to specify known errors.112 """113 114 def __init__(self, message, cls=TemplateSyntaxError):4 unmodified lines119 raise self.error_class(self.message, lineno, filename)120 121 122 class LexerMeta(type):185- """186- Metaclass for the lexer that caches instances for123+ """Metaclass for the lexer that caches instances for124 the same configuration in a weak value dictionary.125 """126 127 def __call__(cls, environment):4 unmodified lines132 environment.comment_start_string,133 environment.comment_end_string,134 environment.line_statement_prefix,135 environment.trim_blocks)199-200- # use the cached lexer if possible201- if key in _lexer_cache:202- return _lexer_cache[key]203-204- # create a new lexer and cache it205- lexer = type.__call__(cls, environment)206- _lexer_cache[key] = lexer136+ lexer = _lexer_cache.get(key)137+ if lexer is None:138+ lexer = type.__call__(cls, environment)139+ _lexer_cache[key] = lexer140 return lexer141 142 143 class Lexer(object):211- """212- Class that implements a lexer for a given environment. Automatically144+ """Class that implements a lexer for a given environment. Automatically145 created by the environment class, usually you don't have to do that.146 147 Note that the lexer is not automatically bound to an environment.148 Multiple environments can share the same lexer.144 unmodified lines293 yield Token(lineno, token, value)294 return TokenStream(generate(), filename)295 296 def tokeniter(self, source, filename=None):297+ """This method tokenizes the text and returns the tokens in a298+ generator. Use this method if you just want to tokenize a template.299+ The output you get is not compatible with the input the jinja parser300+ wants. The parser uses the `tokenize` function with returns a301+ `TokenStream` and postprocessed tokens.302 """366- This method tokenizes the text and returns the tokens in a generator.367- Use this method if you just want to tokenize a template. The output368- you get is not compatible with the input the jinja parser wants. The369- parser uses the `tokenize` function with returns a `TokenStream` and370- keywords instead of just names.371- """303 source = '\n'.join(source.splitlines())304 pos = 0305 lineno = 1306 stack = ['root']126 unmodified linesmodified:jinja2/nodes.py+9 added-6 removed
40 unmodified lines41 'gt': operator.gt,42 'gteq': operator.ge,43 'lt': operator.lt,44 'lteq': operator.le,45- 'in': operator.contains,46- 'notin': lambda a, b: b not in a45+ 'in': lambda a, b: a in b,46+ 'notin': lambda a, b: a not in b47 }48 49 50 class Impossible(Exception):466 unmodified lines517 fields = ('expr', 'ops')518 519 def as_const(self):520 result = value = self.expr.as_const()521+ try:521- for op in self.ops:522- new_value = op.expr.as_const()523- result = _cmpop_to_func[op.op](value, new_value)524- value = new_value522+ for op in self.ops:523+ new_value = op.expr.as_const()524+ result = _cmpop_to_func[op.op](value, new_value)525+ value = new_value526+ except:527+ raise Impossible()528 return result529 530 531 class Operand(Helper):68 unmodified linesmodified:jinja2/parser.py+6 added-9 removed
15 unmodified lines16 _statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',17 'macro', 'include'])18 _compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq', 'in'])19 statement_end_tokens = set(['variable_end', 'block_end', 'in'])20+_tuple_edge_tokens = set(['rparen']) | statement_end_tokens21 22 23 class Parser(object):24 """The template parser class.396 unmodified lines421 is_tuple = False422 while 1:423 if args:424 self.stream.expect('comma')424- if self.stream.current.type in statement_end_tokens:425+ if self.stream.current.type in _tuple_edge_tokens:426 break427 args.append(parse())427- if self.stream.current.type is not 'comma':428+ if self.stream.current.type is 'comma':429+ is_tuple = True430+ else:431 break429- is_tuple = True432 lineno = self.stream.current.lineno433 if not is_tuple and args:434 if enforce:435 raise TemplateSyntaxError('tuple expected', lineno,205 unmodified lines641 add_data(nodes.Const(token.value, lineno=token.lineno))642 self.stream.next()643 elif token.type is 'variable_begin':644 self.stream.next()643- want_comma = False644- while not self.stream.current.test_many(statement_end_tokens):645- if want_comma:646- self.stream.expect('comma')647- add_data(self.parse_expression())645+ add_data(self.parse_tuple())648- want_comma = True646 self.stream.expect('variable_end')647 elif token.type is 'block_begin':648 flush_data()649 self.stream.next()17 unmodified linesmodified:jinja2/runtime.py+12 added-2 removed
33 unmodified lines34 # bind functions to the context of environment if required35 for name, obj in self.parent.iteritems():36 if type(obj) is FunctionType:37 if getattr(obj, 'contextfunction', 0):38- self.vars[key] = partial(obj, self)38+ self.vars[name] = partial(obj, self)39 elif getattr(obj, 'environmentfunction', 0):40- self.vars[key] = partial(obj, environment)40+ self.vars[name] = partial(obj, environment)41 42 # create the initial mapping of blocks. Whenever template inheritance43 # takes place the runtime will update this mapping with the new blocks44 # from the template.10 unmodified lines55 return self.environment.undefined('there is no parent block '56 'called %r.' % block)57 return SuperBlock(block, self, last)58 59+ def get(self, name, default=None):60+ """For dict compatibility"""61+ try:62+ return self[name]63+ except KeyError:64+ return default65+66 def update(self, mapping):67 """Update vars from a mapping but don't export them."""68 self.vars.update(mapping)69 12 unmodified lines82 def __setitem__(self, key, value):83 self.vars[key] = value84 self.exported_vars.add(key)85 86+ def __contains__(self, name):87+ return name in self.vars or name in self.parent88+89 def __getitem__(self, key):90 if key in self.vars:91 return self.vars[key]92 try:261 unmodified linesmodified:tests/test_i18n.py+3 added-3 removed
44 unmodified lines45 46 47 i18n_env = Environment(48 loader=DictLoader(templates),49- extensions=['jinja2.i18n.TransExtension']49+ extensions=['jinja2.ext.TransExtension']50 )51 i18n_env.globals.update({52 '_': gettext,53 'gettext': gettext,17 unmodified lines71 assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'72 73 74 def test_extract():75- from jinja2.i18n import babel_extract75+ from jinja2.ext import babel_extract76 from StringIO import StringIO77 source = StringIO('''78 {{ gettext('Hello World') }}79 {% trans %}Hello World{% endtrans %}80 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}81 ''')82 assert list(babel_extract(source, ('gettext', 'ngettext', '_'), [], {})) == [83- (2, 'gettext', 'Hello World', []),83+ (2, 'gettext', u'Hello World', []),84 (3, 'gettext', u'Hello World', []),85 (4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])86 ]modified:tests/test_macros.py+7 added-33 removed
6 unmodified lines7 :license: BSD, see LICENSE for more details.8 """9 10 SIMPLE = '''\11-{% macro say_hello name %}Hello {{ name }}!{% endmacro %}11+{% macro say_hello(name) %}Hello {{ name }}!{% endmacro %}12 {{ say_hello('Peter') }}\13 '''14 15-KWARGSFAILURE = '''\16-{% macro foo bar %}...{% endmacro %}17-{{ foo(bar='blub') }}\18-'''19-15 SCOPING = '''\21-{% macro level1 data1 %}22-{% macro level2 data2 %}{{ data1 }}|{{ data2 }}{% endmacro %}16+{% macro level1(data1) %}17+{% macro level2(data2) %}{{ data1 }}|{{ data2 }}{% endmacro %}18 {{ level2('bar') }}{% endmacro %}19 {{ level1('foo') }}|{{ level2('bar') }}\20 '''21 22 ARGUMENTS = '''\28-{% macro m a, b, c='c', d='d' %}{{ a }}|{{ b }}|{{ c }}|{{ d }}{% endmacro %}23+{% macro m(a, b, c='c', d='d') %}{{ a }}|{{ b }}|{{ c }}|{{ d }}{% endmacro %}24 {{ m() }}|{{ m('a') }}|{{ m('a', 'b') }}|{{ m(1, 2, 3) }}\25 '''26 32-PARENTHESES = '''\33-{% macro foo(a, b) %}{{ a }}|{{ b }}{% endmacro %}\34-{{ foo(1, 2) }}\35-'''36-27 VARARGS = '''\38-{% macro test %}{{ varargs|join('|') }}{% endmacro %}\28+{% macro test() %}{{ varargs|join('|') }}{% endmacro %}\29 {{ test(1, 2, 3) }}\30 '''31 32 SIMPLECALL = '''\43-{% macro test %}[[{{ caller() }}]]{% endmacro %}\33+{% macro test() %}[[{{ caller() }}]]{% endmacro %}\34 {% call test() %}data{% endcall %}\35 '''36 37 COMPLEXCALL = '''\48-{% macro test %}[[{{ caller(data='data') }}]]{% endmacro %}\38+{% macro test() %}[[{{ caller(data='data') }}]]{% endmacro %}\39 {% call test() %}{{ data }}{% endcall %}\40 '''41 42 CALLERUNDEFINED = '''\9 unmodified lines52 tmpl = env.from_string(SIMPLE)53 assert tmpl.render() == 'Hello Peter!'54 55 66-def test_kwargs_failure(env):67- from jinja2.exceptions import TemplateRuntimeError68- tmpl = env.from_string(KWARGSFAILURE)69- try:70- tmpl.render()71- except TemplateRuntimeError, e:72- pass73- else:74- raise AssertionError('kwargs failure test failed')75-76-56 def test_scoping(env):57 tmpl = env.from_string(SCOPING)58 assert tmpl.render() == 'foo|bar|'59 2 unmodified lines62 tmpl = env.from_string(ARGUMENTS)63 assert tmpl.render() == '||c|d|a||c|d|a|b|c|d|1|2|3|d'64 65 87-def test_parentheses(env):88- tmpl = env.from_string(PARENTHESES)89- assert tmpl.render() == '1|2'90-91-66 def test_varargs(env):67 tmpl = env.from_string(VARARGS)68 assert tmpl.render() == '1|2|3'69 19 unmodified linesmodified:tests/test_syntax.py+1 added-4 removed
34 unmodified lines35 '{{ 1, }}',36 '{{ 1, 2 }}',37 '{% for foo, bar in seq %}...{% endfor %}',38 '{% for x in foo, bar %}...{% endfor %}',39- '{% for x in foo, %}...{% endfor %}',40- '{% for x in foo, recursive %}...{% endfor %}',41- '{% for x in foo, bar recursive %}...{% endfor %}',42- '{% for x, in foo, recursive %}...{% endfor %}'39+ '{% for x in foo, %}...{% endfor %}'40 ]41 TRAILINGCOMMA = '''{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}'''42 43 125 unmodified linesmodified:setup.py+1 added-1 removed
132 unmodified lines133 },134 extras_require={'i18n': ['Babel>=0.8']},135 entry_points="""136 [babel.extractors]137- jinja2 = jinja.i18n:babel_extract[i18n]137+ jinja2 = jinja.ext:babel_extract[i18n]138 """139 )