Skip to content
Myr

reimplemented {% trans %}

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 b9bed15 · Browse files · 9 files+245 added−64 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+245 added−64 removed

  • other:+245 added−64 removed

9 files+245 added−64 removed

added:examples/translate.py+6 added
1from jinja2 import Environment23print Environment().from_string("""\4{% trans %}Hello {{ user }}!{% endtrans %}5{% trans count=users|count %}{{ count }} user{% pluralize %}{{ count }} users{% endtrans %}6""").render()
modified:jinja2/compiler.py+2 added-3 removed
48 unmodified lines
49 """Does the node have a safe representation?"""50 if value is None or value is NotImplemented or value is Ellipsis:51 return True52 if isinstance(value, (bool, int, long, float, complex, basestring,53 StaticLoopContext)):53 xrange, StaticLoopContext)):54 return True55 if isinstance(value, (tuple, list, set, frozenset)):56 for item in value:57 if not has_safe_repr(item):
971 unmodified lines
1029 self.signature(node, frame, False, extra_kwargs)1030 self.write(')')10311032 def visit_Keyword(self, node, frame):1033 self.visit(node.key, frame)1034 self.write('=')1033 self.write(node.key + '=')1034 self.visit(node.value, frame)
modified:jinja2/environment.py+14 added-8 removed
65 unmodified lines
66 represent undefined variables.67 `loader` the loader which should be used.68 ========================= ============================================69 """7071 # santity checks72 assert issubclass(undefined, Undefined), 'undefined must be ' \73 'a subclass of undefined because filters depend on it.'74 assert block_start_string != variable_start_string != \75 comment_start_string, 'block, variable and comment ' \76 'start strings must be different'7778 # lexer / parser information79 self.block_start_string = block_start_string80 self.block_end_string = block_end_string
59 unmodified lines
140 node = optimize(source, self, globals or {})141 source = generate(node, self, filename)142 if raw:143 return source144 if filename is None:145 filename = '<from_string>'139 if isinstance(filename, unicode):146 elif isinstance(filename, unicode):147 filename = filename.encode('utf-8')148 return compile(source, filename, 'exec')149150 def join_path(self, template, parent):
13 unmodified lines
164165 def from_string(self, source, filename='<string>', globals=None):166 """Load a template from a string."""167 globals = self.make_globals(globals)161 return Template(self, self.compile(source, filename), globals)168 return Template(self, self.compile(source, filename, globals=globals),169 globals)170171 def make_globals(self, d):172 """Return a dict for the globals."""173 if d is None:
20 unmodified lines
194 return TemplateStream(self.generate(*args, **kwargs))195196 def generate(self, *args, **kwargs):197 # assemble the context190 local_context = dict(*args, **kwargs)191 context = self.globals.copy()192 context.update(local_context)198 context = dict(*args, **kwargs)199200 # if the environment is using the optimizer locals may never201 # override globals as optimizations might have happened202 # depending on values of certain globals. This assertion goes203 # away if the python interpreter is started with -O204 if __debug__ and self.environment.optimized:199 overrides = set(local_context) & set(self.globals)205 overrides = set(context) & set(self.globals)206 if overrides:207 plural = len(overrides) != 1 and 's' or ''208 raise AssertionError('the per template variable%s %s '209 'override%s global variable%s. '210 'With an enabled optimizer this '211 'will lead to unexpected results.' %212 (plural, ', '.join(overrides), plural or ' a', plural))207 gen = self.root_render_func(context)208 # skip the first item which is a reference to the stream213 gen = self.root_render_func(dict(self.globals, **context))214 # skip the first item which is a reference to the context215 gen.next()216 return gen217218 def __repr__(self):
51 unmodified lines
added:jinja2/i18n.py+155 added
1# -*- coding: utf-8 -*-2"""3 jinja2.i18n4 ~~~~~~~~~~~56 i18n support for Jinja.78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10"""11from jinja2 import nodes12from jinja2.parser import _statement_end_tokens13from jinja2.exceptions import TemplateAssertionError141516def parse_trans(parser):17 """Parse a translatable tag."""18 lineno = parser.stream.expect('trans').lineno1920 # skip colon for python compatibility21 if parser.stream.current.type is 'colon':22 parser.stream.next()2324 # find all the variables referenced. Additionally a variable can be25 # defined in the body of the trans block too, but this is checked at26 # a later state.27 plural_expr = None28 variables = {}29 while parser.stream.current.type is not 'block_end':30 if variables:31 parser.stream.expect('comma')32 name = parser.stream.expect('name')33 if name.value in variables:34 raise TemplateAssertionError('translatable variable %r defined '35 'twice.' % name.value, name.lineno,36 parser.filename)3738 # expressions39 if parser.stream.current.type is 'assign':40 parser.stream.next()41 variables[name.value] = var = parser.parse_expression()42 else:43 variables[name.value] = var = nodes.Name(name.value, 'load')44 if plural_expr is None:45 plural_expr = var46 parser.stream.expect('block_end')4748 plural = plural_names = None49 have_plural = False50 referenced = set()5152 # now parse until endtrans or pluralize53 singular_names, singular = _parse_block(parser, True)54 if singular_names:55 referenced.update(singular_names)56 if plural_expr is None:57 plural_expr = nodes.Name(singular_names[0], 'load')5859 # if we have a pluralize block, we parse that too60 if parser.stream.current.type is 'pluralize':61 have_plural = True62 parser.stream.next()63 if parser.stream.current.type is not 'block_end':64 plural_expr = parser.parse_expression()65 parser.stream.expect('block_end')66 plural_names, plural = _parse_block(parser, False)67 parser.stream.next()68 referenced.update(plural_names)69 else:70 parser.stream.next()71 parser.end_statement()7273 # register free names as simple name expressions74 for var in referenced:75 if var not in variables:76 variables[var] = nodes.Name(var, 'load')7778 # no variables referenced? no need to escape79 if not referenced:80 singular = singular.replace('%%', '%')81 if plural:82 plural = plural.replace('%%', '%')8384 if not have_plural:85 if plural_expr is None:86 raise TemplateAssertionError('pluralize without variables',87 lineno, parser.filename)88 plural_expr = None8990 if variables:91 variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)92 for x, y in variables.items()])93 else:94 vairables = None9596 node = _make_node(singular, plural, variables, plural_expr)97 node.set_lineno(lineno)98 return node99100101def _parse_block(parser, allow_pluralize):102 """Parse until the next block tag with a given name."""103 referenced = []104 buf = []105 while 1:106 if parser.stream.current.type is 'data':107 buf.append(parser.stream.current.value.replace('%', '%%'))108 parser.stream.next()109 elif parser.stream.current.type is 'variable_begin':110 parser.stream.next()111 referenced.append(parser.stream.expect('name').value)112 buf.append('%s')113 parser.stream.expect('variable_end')114 elif parser.stream.current.type is 'block_begin':115 parser.stream.next()116 if parser.stream.current.type is 'endtrans':117 break118 elif parser.stream.current.type is 'pluralize':119 if allow_pluralize:120 break121 raise TemplateSyntaxError('a translatable section can have '122 'only one pluralize section',123 parser.stream.current.lineno,124 parser.filename)125 raise TemplateSyntaxError('control structures in translatable '126 'sections are not allowed.',127 parser.stream.current.lineno,128 parser.filename)129 else:130 assert False, 'internal parser error'131132 return referenced, u''.join(buf)133134135def _make_node(singular, plural, variables, plural_expr):136 """Generates a useful node from the data provided."""137 # singular only:138 if plural_expr is None:139 gettext = nodes.Name('gettext', 'load')140 node = nodes.Call(gettext, [nodes.Const(singular)],141 [], None, None)142 if variables:143 node = nodes.Mod(node, variables)144145 # singular and plural146 else:147 ngettext = nodes.Name('ngettext', 'load')148 node = nodes.Call(ngettext, [149 nodes.Const(singular),150 nodes.Const(plural),151 plural_expr152 ], [], None, None)153 if variables:154 node = nodes.Mod(node, variables)155 return nodes.Output([node])
modified:jinja2/lexer.py+13 added-32 removed
234 unmodified lines
235 (string_re, 'string', None),236 (operator_re, 'operator', None)237 ]238239 #: if variables and blocks have the same delimiters we won't240 #: receive any variable blocks in the parser. This variable is `True`241 #: if we need that.242 self.no_variable_block = (243 (environment.variable_start_string is244 environment.variable_end_string is None) or245 (environment.variable_start_string ==246 environment.block_start_string and247 environment.variable_end_string ==248 environment.block_end_string)249 )250239 # assamble the root lexing rule. because "|" is ungreedy240 # we have to sort by length so that the lexer continues working241 # as expected when we have parsing rules like <% for block and242 # <%= for variables. (if someone wants asp like syntax)243 # variables are just part of the rules if variable processing244 # is required.245 root_tag_rules = [246 ('comment', environment.comment_start_string),259 ('block', environment.block_start_string)247 ('block', environment.block_start_string),248 ('variable', environment.variable_start_string)249 ]261 if not self.no_variable_block:262 root_tag_rules.append(('variable',263 environment.variable_start_string))250 root_tag_rules.sort(key=lambda x: len(x[1]))251252 # now escape the rules. This is done here so that the escape253 # signs don't count for the lengths of the tags.
40 unmodified lines
294 e(environment.block_end_string),295 block_suffix_re296 )), 'block_end', '#pop'),297 ] + tag_rules,298 # variables299 'variable_begin': [300 (c('\-%s\s*|%s' % (301 e(environment.variable_end_string),302 e(environment.variable_end_string)303 )), 'variable_end', '#pop')304 ] + tag_rules,305 # raw block306 'raw_begin': [307 (c('(.*?)((?:\s*%s\-|%s)\s*endraw\s*(?:\-%s\s*|%s%s))' % (308 e(environment.block_start_string),
2 unmodified lines
311 e(environment.block_end_string),312 block_suffix_re313 )), ('data', 'raw_end'), '#pop'),314 (c('(.)'), (Failure('Missing end of raw directive'),), None)322 ]323 }324325 # only add the variable rules to the list if we process variables326 # the variable_end_string variable could be None and break things.327 if not self.no_variable_block:328 self.rules['variable_begin'] = [329 (c('\-%s\s*|%s' % (330 e(environment.variable_end_string),331 e(environment.variable_end_string)332 )), 'variable_end', '#pop')333 ] + tag_rules334335 # the same goes for the line_statement_prefix336 if environment.line_statement_prefix is not None:337 self.rules['linestatement_begin'] = [315 ],316 # line statements317 'linestatement_begin': [318 (c(r'\s*(\n|$)'), 'linestatement_end', '#pop')319 ] + tag_rules320 }321322 def tokenize(self, source, filename=None):323 """Works like `tokeniter` but returns a tokenstream of tokens and not324 a generator or token tuples. Additionally all token values are already
175 unmodified lines
modified:jinja2/nodes.py+12 added-1 removed
157 unmodified lines
158 if 'ctx' in node.fields:159 node.ctx = ctx160 todo.extend(node.iter_child_nodes())161162 def set_lineno(self, lineno, override=False):163 """Set the line numbers of the node and children."""164 todo = deque([self])165 while todo:166 node = todo.popleft()167 if 'lineno' in node.attributes:168 if node.lineno is None or override:169 node.lineno = lineno170 todo.extend(node.iter_child_nodes())171172 def set_environment(self, environment):173 """Set the environment for all nodes."""174 todo = deque([self])175 while todo:
166 unmodified lines
342 @classmethod343 def from_untrusted(cls, value, lineno=None, environment=None):344 """Return a const object if the value is representable as345 constant value in the generated code, otherwise it will raise336 an `Impossible` exception."""346 an `Impossible` exception.347 """348 from compiler import has_safe_repr349 if not has_safe_repr(value):350 raise Impossible()351 return cls(value, lineno=lineno, environment=environment)
234 unmodified lines
modified:jinja2/optimizer.py+11 added-1 removed
14 unmodified lines
15 be saved again for later rendering. But even if you don't want to16 prerender a template, this module might speed up your templates a bit17 if you are using a lot of constants.1819 :copyright: Copyright 2008 by Christoph Hack.19 :copyright: Copyright 2008 by Christoph Hack, Armin Ronacher.20 :license: GNU GPL.21"""22from jinja2 import nodes23from jinja2.visitor import NodeVisitor, NodeTransformer24from jinja2.runtime import LoopContext252627# TODO28# - function calls to contant objects are not properly evaluated if the29# function is not representable at constant type. eg:30# {% for item in range(10) %} doesn't become31# for l_item in xrange(10: even though it would be possible32# - multiple Output() nodes should be concatenated into one node.33# for example the i18n system could output such nodes:34# "foo{% trans %}bar{% endtrans %}blah"353637def optimize(node, environment, context_hint=None):38 """The context hint can be used to perform an static optimization39 based on the context given."""40 optimizer = Optimizer(environment)
227 unmodified lines
modified:jinja2/parser.py+8 added-2 removed
11 unmodified lines
12from jinja2.exceptions import TemplateSyntaxError131415_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',16 'macro', 'include'])16 'macro', 'include', 'trans'])17_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq', 'in'])18_statement_end_tokens = set(['elif', 'else', 'endblock', 'endfilter',19 'endfor', 'endif', 'endmacro', 'variable_end',20 'in', 'recursive', 'endcall', 'block_end'])
11 unmodified lines
32 filename = filename.encode('utf-8')33 self.source = unicode(source)34 self.filename = filename35 self.closed = False36 self.no_variable_block = self.environment.lexer.no_variable_block36 self.stream = environment.lexer.tokenize(source, filename)3738 def end_statement(self):39 """Make sure that the statement ends properly."""
193 unmodified lines
233 node.nodes.append(self.parse_expression())234 self.end_statement()235 return node236237 def parse_trans(self):238 """Parse a translatable section."""239 # lazily imported because we don't want the i18n overhead240 # if it's not used. (Even though the overhead is low)241 from jinja2.i18n import parse_trans242 return parse_trans(self)243244 def parse_expression(self, no_condexpr=False):245 """Parse an expression."""246 if no_condexpr:247 return self.parse_or()
443 unmodified lines
modified:jinja2/runtime.py+24 added-17 removed
135 unmodified lines
136 self._length = None137 self.index0 = 0138 self.parent = parent139140 def cycle(self, *args):141 """A replacement for the old ``{% cycle %}`` tag."""142 if not args:143 raise TypeError('no items for cycling given')144 return args[self.index0 % len(args)]145146 first = property(lambda x: x.index0 == 0)147 last = property(lambda x: x.revindex0 == 0)148 index = property(lambda x: x.index0 + 1)149 revindex = property(lambda x: x.length)150 revindex0 = property(lambda x: x.length - 1)145 length = property(lambda x: len(x))151152 def __len__(self):153 return self.length154155156class LoopContext(LoopContextBase):157 """A loop context for dynamic iteration."""158159 def __init__(self, iterable, parent=None, enforce_length=False):
18 unmodified lines
178 def next(self):179 self.index0 += 1180 return self._next(), self181182 @property174 def __len__(self):183 def length(self):184 if self._length is None:185 try:186 length = len(self._iterable)187 except TypeError:
2 unmodified lines
190 length = len(tuple(self._iterable)) + self.index0 + 1191 self._length = length192 return self._length193194 def __repr__(self):195 return 'LoopContext(%r)' % self.index0196197198class StaticLoopContext(LoopContextBase):199 """The static loop context is used in the optimizer to "freeze" the200 status of an iteration. The only reason for this object is if the201 loop object is accessed in a non static way (eg: becomes part of a
1 unmodified line
203204 def __init__(self, index0, length, parent):205 self.index0 = index0206 self.parent = parent195 self._length = length207 self.length = length208209 def __repr__(self):210 """The repr is used by the optimizer to dump the object."""211 return 'StaticLoopContext(%r, %r, %r)' % (212 self.index0,201 self._length,213 self.length,214 self.parent215 )216205 def __len__(self):206 return self._length207217 def make_static(self):218 return self219220
54 unmodified lines
275276 def __init__(self, name=None, attr=None, extra=None):277 if attr is None:278 self._undefined_hint = '%r is undefined' % name279 self._error_class = NameError280 else:271 self._undefined_hint = 'attribute %r of %r is undefined' \272 % (attr, name)281 self._undefined_hint = '%r has no attribute named %r' \282 % (name, attr)283 self._error_class = AttributeError284 if extra is not None:285 self._undefined_hint += ' (' + extra + ')'286276 def fail_with_error(self, *args, **kwargs):277 raise NameError(self._undefined_hint)287 def _fail_with_error(self, *args, **kwargs):288 raise self._error_class(self._undefined_hint)289 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \290 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \291 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \281 __getattr__ = __getitem__ = fail_with_error282 del fail_with_error292 __getattr__ = __getitem__ = _fail_with_error293294 def __unicode__(self):295 return u''296
23 unmodified lines
320321class StrictUndefined(Undefined):322 """An undefined that barks on print and iteration."""323314 def fail_with_error(self, *args, **kwargs):315 raise NameError(self._undefined_hint)316 __iter__ = __unicode__ = __len__ = fail_with_error324 __iter__ = __unicode__ = __len__ = Undefined._fail_with_error317 del fail_with_error