refactored extensions a bit
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 f59bac2 · Browse files · 6 files·+195 added−158 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+195 added−158 removed
- other:+195 added−158 removed
Provenance
- Commit
0553093- Tree
7503cae- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
f59bac2
6 files changed+195 added−158 removed
modified:examples/translate.py+1 added-1 removed
1 from jinja2 import Environment2 3-print Environment(parser_extensions=['jinja2.i18n.trans']).from_string("""\3+print Environment(extensions=['jinja2.i18n.TransExtension']).from_string("""\4 {% trans %}Hello {{ user }}!{% endtrans %}5 {% trans count=users|count %}{{ count }} user{% pluralize %}{{ count }} users{% endtrans %}6 """).render(user="someone")modified:jinja2/defaults.py+1 added-5 removed
11 unmodified lines12 from jinja2.tests import TESTS as DEFAULT_TESTS13 14 15 DEFAULT_NAMESPACE = {16- 'range': xrange,17- # fake translators so that {% trans %} is a noop by default18- '_': lambda x: x,19- 'gettext': lambda x: x,20- 'ngettext': lambda s, p, n: (s, p)[n != 1]16+ 'range': xrange17 }modified:jinja2/environment.py+8 added-7 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import sys12 from jinja2.lexer import Lexer13-from jinja2.parser import Parser, ParserExtension13+from jinja2.parser import Parser14 from jinja2.optimizer import optimize15 from jinja2.compiler import generate16 from jinja2.runtime import Undefined17 from jinja2.debug import translate_exception25 unmodified lines43 trim_blocks=False,44 optimized=True,45 undefined=Undefined,46 loader=None,47- parser_extensions=(),47+ extensions=(),48 finalize=unicode):49 """Here the possible initialization parameters:50 51 ========================= ============================================17 unmodified lines69 ``True``.70 `undefined` a subclass of `Undefined` that is used to71 represent undefined variables.72 `loader` the loader which should be used.73- `parser_extensions` List of parser extensions to use.73+ `extensions` List of Jinja extensions to use.74 `finalize` A callable that finalizes the variable. Per75 default this is `unicode`, other useful76 builtin finalizers are `escape`.77 ========================= ============================================14 unmodified lines92 self.comment_start_string = comment_start_string93 self.comment_end_string = comment_end_string94 self.line_statement_prefix = line_statement_prefix95 self.trim_blocks = trim_blocks96- self.parser_extensions = {}97- for extension in parser_extensions:96+ self.extensions = []97+ for extension in extensions:98 if isinstance(extension, basestring):99 extension = import_string(extension)100- self.parser_extensions[extension.tag] = extension100+ self.extensions.append(extension(self))101 102-102 # runtime information103 self.undefined = undefined104 self.optimized = optimized105 self.finalize = finalize1 unmodified line107 # defaults108 self.filters = DEFAULT_FILTERS.copy()109 self.tests = DEFAULT_TESTS.copy()110 self.globals = DEFAULT_NAMESPACE.copy()111+ for extension in self.extensions:112+ extension.update_globals(self.globals)113 114 # set the loader provided115 self.loader = loader116 214 unmodified linesadded:jinja2/ext.py+48 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja2.ext4+ ~~~~~~~~~~5+6+ Jinja extensions (EXPERIMENAL)7+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+13+ :copyright: Copyright 2008 by Armin Ronacher.14+ :license: BSD.15+"""16+from jinja2 import nodes17+18+19+class Extension(object):20+ """Instances of this class store parser extensions."""21+22+ #: if this extension parses this is the list of tags it's listening to.23+ tags = set()24+25+ def __init__(self, environment):26+ self.environment = environment27+28+ def update_globals(self, globals):29+ """Called to inject runtime variables into the globals."""30+ pass31+32+ def parse(self, parser):33+ """Called if one of the tags matched."""34+35+36+class CacheExtension(Extension):37+ tags = set(['cache'])38+39+ def parse(self, parser):40+ lineno = parser.stream.next().lineno41+ args = [parser.parse_expression()]42+ if self.stream.current.type is 'comma':43+ args.append(parser.parse_expression())44+ body = parser.parse_statements(('name:endcache',), drop_needle=True)45+ return nodes.CallBlock(46+ nodes.Call(nodes.Name('cache_support'), args, [], None, None),47+ [], [], body48+ )modified:jinja2/i18n.py+133 added-127 removed
9 unmodified lines10 """11 from collections import deque12 from jinja2 import nodes13 from jinja2.environment import Environment14-from jinja2.parser import ParserExtension, statement_end_tokens14+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. Note61 unmodified lines81 for lineno, func, message in extract_from_ast(node, keywords):82 yield lineno, func, message, []83 84 84-def parse_trans(parser):85- """Parse a translatable tag."""86- lineno = parser.stream.next().lineno85+class TransExtension(Extension):86+ tags = set(['trans'])87 88- # skip colon for python compatibility89- if parser.stream.current.type is 'colon':90- parser.stream.next()88+ def update_globals(self, globals):89+ """Inject noop translation functions."""90+ globals.update({91+ '_': lambda x: x,92+ 'gettext': lambda x: x,93+ 'ngettext': lambda s, p, n: (s, p)[n != 1]94+ })95 92- # find all the variables referenced. Additionally a variable can be93- # defined in the body of the trans block too, but this is checked at94- # a later state.95- plural_expr = None96- variables = {}97- while parser.stream.current.type is not 'block_end':98- if variables:99- parser.stream.expect('comma')100- name = parser.stream.expect('name')101- if name.value in variables:102- raise TemplateAssertionError('translatable variable %r defined '103- 'twice.' % name.value, name.lineno,104- parser.filename)96+ def parse(self, parser):97+ """Parse a translatable tag."""98+ lineno = parser.stream.next().lineno99 106- # expressions107- if parser.stream.current.type is 'assign':100+ # skip colon for python compatibility101+ if parser.stream.current.type is 'colon':102 parser.stream.next()109- variables[name.value] = var = parser.parse_expression()110- else:111- variables[name.value] = var = nodes.Name(name.value, 'load')112- if plural_expr is None:113- plural_expr = var114- parser.stream.expect('block_end')103 116- plural = plural_names = None117- have_plural = False118- referenced = set()104+ # find all the variables referenced. Additionally a variable can be105+ # defined in the body of the trans block too, but this is checked at106+ # a later state.107+ plural_expr = None108+ variables = {}109+ while parser.stream.current.type is not 'block_end':110+ if variables:111+ parser.stream.expect('comma')112+ name = parser.stream.expect('name')113+ if name.value in variables:114+ raise TemplateAssertionError('translatable variable %r defined '115+ 'twice.' % name.value, name.lineno,116+ parser.filename)117 120- # now parse until endtrans or pluralize121- singular_names, singular = _parse_block(parser, True)122- if singular_names:123- referenced.update(singular_names)124- if plural_expr is None:125- plural_expr = nodes.Name(singular_names[0], 'load')126-127- # if we have a pluralize block, we parse that too128- if parser.stream.current.test('name:pluralize'):129- have_plural = True130- parser.stream.next()131- if parser.stream.current.type is not 'block_end':132- plural_expr = parser.parse_expression()118+ # expressions119+ if parser.stream.current.type is 'assign':120+ parser.stream.next()121+ variables[name.value] = var = parser.parse_expression()122+ else:123+ variables[name.value] = var = nodes.Name(name.value, 'load')124+ if plural_expr is None:125+ plural_expr = var126 parser.stream.expect('block_end')134- plural_names, plural = _parse_block(parser, False)135- parser.stream.next()136- referenced.update(plural_names)137- else:138- parser.stream.next()139- parser.end_statement()127 141- # register free names as simple name expressions142- for var in referenced:143- if var not in variables:144- variables[var] = nodes.Name(var, 'load')128+ plural = plural_names = None129+ have_plural = False130+ referenced = set()131 146- # no variables referenced? no need to escape147- if not referenced:148- singular = singular.replace('%%', '%')149- if plural:150- plural = plural.replace('%%', '%')132+ # now parse until endtrans or pluralize133+ singular_names, singular = self._parse_block(parser, True)134+ if singular_names:135+ referenced.update(singular_names)136+ if plural_expr is None:137+ plural_expr = nodes.Name(singular_names[0], 'load')138 152- if not have_plural:153- if plural_expr is None:154- raise TemplateAssertionError('pluralize without variables',155- lineno, parser.filename)156- plural_expr = None157-158- if variables:159- variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)160- for x, y in variables.items()])161- else:162- vairables = None163-164- node = _make_node(singular, plural, variables, plural_expr)165- node.set_lineno(lineno)166- return node167-168-169-def _parse_block(parser, allow_pluralize):170- """Parse until the next block tag with a given name."""171- referenced = []172- buf = []173- while 1:174- if parser.stream.current.type is 'data':175- buf.append(parser.stream.current.value.replace('%', '%%'))139+ # if we have a pluralize block, we parse that too140+ if parser.stream.current.test('name:pluralize'):141+ have_plural = True142 parser.stream.next()177- elif parser.stream.current.type is 'variable_begin':143+ if parser.stream.current.type is not 'block_end':144+ plural_expr = parser.parse_expression()145+ parser.stream.expect('block_end')146+ plural_names, plural = self._parse_block(parser, False)147 parser.stream.next()179- name = parser.stream.expect('name').value180- referenced.append(name)181- buf.append('%%(%s)s' % name)182- parser.stream.expect('variable_end')183- elif parser.stream.current.type is 'block_begin':184- parser.stream.next()185- if parser.stream.current.test('name:endtrans'):186- break187- elif parser.stream.current.test('name:pluralize'):188- if allow_pluralize:189- break190- raise TemplateSyntaxError('a translatable section can have '191- 'only one pluralize section',192- parser.stream.current.lineno,193- parser.filename)194- raise TemplateSyntaxError('control structures in translatable '195- 'sections are not allowed.',196- parser.stream.current.lineno,197- parser.filename)148+ referenced.update(plural_names)149 else:199- assert False, 'internal parser error'150+ parser.stream.next()151+ parser.end_statement()152 201- return referenced, u''.join(buf)153+ # register free names as simple name expressions154+ for var in referenced:155+ if var not in variables:156+ variables[var] = nodes.Name(var, 'load')157 158+ # no variables referenced? no need to escape159+ if not referenced:160+ singular = singular.replace('%%', '%')161+ if plural:162+ plural = plural.replace('%%', '%')163 204-def _make_node(singular, plural, variables, plural_expr):205- """Generates a useful node from the data provided. The nodes won't have206- a line number information so the caller must set it via `set_lineno` later.207- """208- # singular only:209- if plural_expr is None:210- gettext = nodes.Name('gettext', 'load')211- node = nodes.Call(gettext, [nodes.Const(singular)],212- [], None, None)213- if variables:214- node = nodes.Mod(node, variables)164+ if not have_plural:165+ if plural_expr is None:166+ raise TemplateAssertionError('pluralize without variables',167+ lineno, parser.filename)168+ plural_expr = None169 216- # singular and plural217- else:218- ngettext = nodes.Name('ngettext', 'load')219- node = nodes.Call(ngettext, [220- nodes.Const(singular),221- nodes.Const(plural),222- plural_expr223- ], [], None, None)170 if variables:225- node = nodes.Mod(node, variables)226- return nodes.Output([node])171+ variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)172+ for x, y in variables.items()])173+ else:174+ vairables = None175 176+ node = self._make_node(singular, plural, variables, plural_expr)177+ node.set_lineno(lineno)178+ return node179 229-trans = ParserExtension('trans', parse_trans)180+ def _parse_block(self, parser, allow_pluralize):181+ """Parse until the next block tag with a given name."""182+ referenced = []183+ buf = []184+ while 1:185+ if parser.stream.current.type is 'data':186+ buf.append(parser.stream.current.value.replace('%', '%%'))187+ parser.stream.next()188+ elif parser.stream.current.type is 'variable_begin':189+ parser.stream.next()190+ name = parser.stream.expect('name').value191+ referenced.append(name)192+ buf.append('%%(%s)s' % name)193+ parser.stream.expect('variable_end')194+ elif parser.stream.current.type is 'block_begin':195+ parser.stream.next()196+ if parser.stream.current.test('name:endtrans'):197+ break198+ elif parser.stream.current.test('name:pluralize'):199+ if allow_pluralize:200+ break201+ raise TemplateSyntaxError('a translatable section can '202+ 'have only one pluralize '203+ 'section',204+ parser.stream.current.lineno,205+ parser.filename)206+ raise TemplateSyntaxError('control structures in translatable'207+ ' sections are not allowed.',208+ parser.stream.current.lineno,209+ parser.filename)210+ else:211+ assert False, 'internal parser error'212+213+ return referenced, u''.join(buf)214+215+ def _make_node(self, singular, plural, variables, plural_expr):216+ """Generates a useful node from the data provided."""217+ # singular only:218+ if plural_expr is None:219+ gettext = nodes.Name('gettext', 'load')220+ node = nodes.Call(gettext, [nodes.Const(singular)],221+ [], None, None)222+ if variables:223+ node = nodes.Mod(node, variables)224+225+ # singular and plural226+ else:227+ ngettext = nodes.Name('ngettext', 'load')228+ node = nodes.Call(ngettext, [229+ nodes.Const(singular),230+ nodes.Const(plural),231+ plural_expr232+ ], [], None, None)233+ if variables:234+ node = nodes.Mod(node, variables)235+ return nodes.Output([node])modified:jinja2/parser.py+4 added-18 removed
33 unmodified lines34 self.source = unicode(source)35 self.filename = filename36 self.closed = False37 self.stream = environment.lexer.tokenize(source, filename)38- self.extensions = environment.parser_extensions38+ self.extensions = {}39+ for extension in environment.extensions:40+ for tag in extension.tags:41+ self.extensions[tag] = extension.parse42 43 def end_statement(self):44 """Make sure that the statement ends properly."""45 if self.stream.current.type is 'semicolon':642 unmodified lines688 """Parse the whole template into a `Template` node."""689 result = nodes.Template(self.subparse(), lineno=1)690 result.set_environment(self.environment)691 return result689-690-691-class ParserExtension(tuple):692- """Instances of this class store parser extensions."""693- __slots__ = ()694-695- def __new__(cls, tag, parse_func):696- return tuple.__new__(cls, (tag, parse_func))697-698- def __call__(self, parser):699- return self.parse_func(parser)700-701- def __repr__(self):702- return '<%s %r>' % (self.__class__.__name__, self.tag)703-704- tag = property(itemgetter(0))705- parse_func = property(itemgetter(1))