Skip to content
Myr

[svn] final jinja changes for today: implemented better filter lookup

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 eb1fbdf · Browse files · 6 files+191 added−47 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+191 added−47 removed

  • other:+191 added−47 removed

6 files+191 added−47 removed

modified:jinja/translators/python.py+102 added-6 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from compiler import ast12from jinja import nodes13from jinja.exceptions import TemplateSyntaxError141516class PythonTranslator(object):17 """
5 unmodified lines
23 self.node = node24 self.indention = 025 self.last_pos = 02627 self.constants = {28 'true': 'True',29 'false': 'False',30 'none': 'None',31 'undefined': 'Undefined'32 }3334 self.handlers = {35 # jinja nodes36 nodes.Text: self.handle_template_text,37 nodes.NodeList: self.handle_node_list,
14 unmodified lines
52 ast.Sub: self.handle_sub,53 ast.Div: self.handle_div,54 ast.Mul: self.handle_mul,55 ast.Mod: self.handle_mod,56 ast.UnaryAdd: self.handle_unary_add,57 ast.UnarySub: self.handle_unary_sub,58 ast.Power: self.handle_power,59 ast.Dict: self.handle_dict,60 ast.List: self.handle_list,61 ast.Tuple: self.handle_list,62 ast.And: self.handle_and,63 ast.Or: self.handle_or,55 ast.Not: self.handle_not64 ast.Not: self.handle_not,65 ast.Slice: self.handle_slice,66 ast.Sliceobj: self.handle_sliceobj67 }6869 self.unsupported = {70 ast.ListComp: 'list comprehensions',71 ast.From: 'imports',72 ast.Import: 'imports',73 }74 if hasattr(ast, 'GenExpr'):75 self.unsupported.update({76 ast.GenExpr: 'generator expressions'77 })7879 def indent(self, text):80 """81 Indent the current text.82 """
4 unmodified lines
87 Handle one node88 """89 if node.__class__ in self.handlers:90 out = self.handlers[node.__class__](node)91 elif node.__class__ in self.unsupported:92 raise TemplateSyntaxError('unsupported syntax element %r found.'93 % self.unsupported[node.__class__],94 self.last_pos)95 else:96 raise AssertionError('unhandled node %r' % node.__class__)97 return out98
75 unmodified lines
174 def handle_name(self, node):175 """176 Handle name assignments and name retreivement.177 """178 if node.name in self.constants:179 return self.constants[node.name]180 return 'context[%r]' % node.name181182 def handle_compare(self, node):183 """
19 unmodified lines
203 if len(node.subs) != 1:204 raise TemplateSyntaxError('attribute access requires one argument',205 self.last_pos)206 assert node.flags != 'OP_DELETE', 'wtf? do we support that?'207 if node.subs[0].__class__ is ast.Sliceobj:208 return '%s[%s]' % (209 self.handle_node(node.expr),210 self.handle_node(node.subs[0])211 )180 return 'get_attribute(%s, %s)' % (212 return 'environment.get_attribute(%s, %s)' % (213 self.handle_node(node.expr),214 self.handle_node(node.subs[0])215 )216217 def handle_getattr(self, node):218 """219 Handle hardcoded attribute access. foo.bar220 """189 return 'get_attribute(%s, %r)' % (221 return 'environment.get_attribute(%s, %r)' % (222 self.handle_node(node.expr),223 node.attrname224 )225
6 unmodified lines
232 def handle_bitor(self, node):233 """234 We use the pipe operator for filtering.235 """236 filters = []237 for n in node.nodes[1:]:238 if n.__class__ is ast.CallFunc:239 args = []240 for arg in n.args:241 if arg.__class__ is ast.Keyword:242 raise TemplateSyntaxError('keyword arguments for '243 'filters are not supported.',244 self.last_pos)245 args.append(self.handle_node(arg))246 if n.star_args is not None or n.dstar_args is not None:247 raise TemplateSynaxError('*args / **kwargs is not supported '248 'for filters', self.last_pos)249 args = ', '.join(args)250 if args:251 args = ', ' + args252 filters.append('environment.prepare_filter(%s%s)' % (253 self.handle_node(n.node),254 args255 ))256 elif n.__class__ is ast.Name:257 filters.append('environment.prepare_filter(%s)' %258 self.handle_node(n))259 else:260 raise TemplateSyntaxError('invalid filter. filter must be a '261 'hardcoded function name from the '262 'filter namespace',263 self.last_pos)204 return 'environment.apply_filters(%s, [%s])' % (264 return 'environment.apply_filters(%s, context, [%s])' % (265 self.handle_node(node.nodes[0]),206 ', '.join([self.handle_node(n) for n in node.nodes[1:]])266 ', '.join(filters)267 )268269 def handle_call_func(self, node):270 """
63 unmodified lines
334 self.handle_node(node.left),335 self.handle_node(node.right)336 )337338 def handle_unary_add(self, node):339 """340 One of the more or less unused nodes.341 """342 return '(+%s)' % self.handle_node(node.expr)343344 def handle_unary_sub(self, node):345 """346 Make a number negative.347 """
23 unmodified lines
371 """372 We don't know tuples, tuples are lists for jinja.373 """374 return '[%s]' % ', '.join([309 self.handle_node(n) for n in nodes375 self.handle_node(n) for n in node.nodes376 ])377378 def handle_and(self, node):379 """
16 unmodified lines
396 handle not operator.397 """398 return 'not %s' % self.handle_node(node.expr)399400 def handle_slice(self, node):401 """402 Slice access.403 """404 if node.lower is None:405 lower = ''406 else:407 lower = self.handle_node(node.lower)408 if node.upper is None:409 upper = ''410 else:411 upper = self.handle_node(node.upper)412 assert node.flags != 'OP_DELETE', 'wtf? shouldn\'t happen'413 return '%s[%s:%s]' % (414 self.handle_node(node.expr),415 lower,416 upper417 )418419 def handle_sliceobj(self, node):420 """421 Extended Slice access.422 """423 args = []424 for n in node.nodes:425 args.append(self.handle_node(n))426 return '[%s]' % ':'.join(args)427428 def translate(self):429 self.indention = 1430 self.last_pos = 0431 lines = [432 'from jinja.datastructures import Undefined',433 'def generate(environment, context, write, write_var=None):',434 ' """This function was automatically generated by',435 ' the jinja python translator. do not edit."""',436 ' if write_var is None:',
11 unmodified lines
modified:jinja/datastructure.py+38 added-5 removed
77 unmodified lines
78 except:79 raise TypeError('%r requires environment as first argument. '80 'The rest of the arguments are forwarded to '81 'the default dict constructor.')82 initial.update(83 false=False,84 true=True,85 none=None86 )82 self._stack = [initial, {}]8384 def pop(self):85 if len(self._stack) <= 2:
23 unmodified lines
109 tmp[key] = value110 return 'Context(%s)' % repr(tmp)111112113class LoopContext(object):114 """115 Simple class that provides special loop variables.116 Used by `Environment.iterate`.117 """118119 def __init__(self, index, length):120 self.index = 0121 self.length = length122 try:123 self.length = len(seq)124 except TypeError:125 self.seq = list(seq)126 self.length = len(self.seq)127 else:128 self.seq = seq129130 def revindex(self):131 return self.length - self.index + 1132 revindex = property(revindex)133134 def revindex0(self):135 return self.length - self.index136 revindex0 = property(revindex0)137138 def index0(self):139 return self.index - 1140 index0 = property(index0)141142 def even(self):143 return self.index % 2 == 0144 even = property(even)145146 def odd(self):147 return self.index % 2 == 1148 odd = property(odd)149150151class TokenStream(object):152 """153 A token stream works like a normal generator just that154 it supports pushing tokens back to the stream.
54 unmodified lines
modified:jinja/environment.py+45 added-11 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from jinja.lexer import Lexer12from jinja.parser import Parser13from jinja.datastructure import LoopContext, Undefined13from jinja.exceptions import TagNotFound, FilterNotFound14from jinja.exceptions import FilterNotFound15from jinja.defaults import DEFAULT_FILTERS161718class Environment(object):
10 unmodified lines
29 comment_end_string='#}',30 template_charset='utf-8',31 charset='utf-8',32 loader=None,32 tags=None,33 filters=None):3435 # lexer / parser information36 self.block_start_string = block_start_string
16 unmodified lines
53 """Function that creates a new parser and parses the source."""54 parser = Parser(self, source)55 return parser.parse_page()5657 def get_filter(self, name):58 """59 Return the filter for a given name. Raise a `FilterNotFound` exception60 if the requested filter is not registered.61 """62 if name not in self._filters:63 raise FilterNotFound(name)64 return self._filters[name]6557 def to_unicode(self, value):58 """59 Convert a value to unicode with the rules defined on the environment.60 """
3 unmodified lines
64 try:65 return unicode(value)66 except UnicodeError:67 return str(value).decode(self.charset, 'ignore')6869 def iterate(self, seq):70 """71 Helper function used by the python translator runtime code to72 iterate over a sequence.73 """74 try:75 length = len(seq)76 except TypeError:77 seq = list(seq)78 length = len(seq)79 loop_data = LoopContext(0, length)80 for item in seq:81 loop_data.index += 182 yield loop_data, item8384 def prepare_filter(self, name, *args):85 """86 Prepare a filter.87 """88 try:89 return self.filters[name](*args)90 except KeyError:91 raise FilterNotFound(name)9293 def apply_filters(self, value, context, filters):94 """95 Apply a list of filters on the variable.96 """97 for f in filters:98 value = f(self, context, value)99 return value100101 def get_attribute(self, obj, name):102 """103 Get the attribute name from obj.104 """105 try:106 return getattr(obj, name)107 except AttributeError:108 return obj[name]109 except:110 return Undefined
modified:jinja/exceptions.py+5 added-17 removed
12 unmodified lines
13class TemplateError(RuntimeError):14 pass151617class TagNotFound(KeyError, TemplateError):18 """19 The parser looked for a specific tag in the tag library but was unable to find20 one.21 """2223 def __init__(self, tagname):24 super(TagNotFound, self).__init__('The tag %r does not exist.' % tagname)25 self.tagname = tagname262717class FilterNotFound(KeyError, TemplateError):18 """30 The template engine looked for a filter but was unable to find it.19 Raised if a filter does not exist.20 """2133 def __init__(self, filtername):34 super(FilterNotFound, self).__init__('The filter %r does not exist.' % filtername)35 self.filtername = filtername22 def __init__(self, message):23 KeyError.__init__(self, message)242526class TemplateSyntaxError(SyntaxError, TemplateError):27 """28 Raised to tell the user that there is a problem with the template.29 """3031 def __init__(self, message, pos):44 super(TemplateSyntaxError, self).__init__(message)32 SyntaxError.__init__(self, message)33 self.pos = pos343536class TemplateRuntimeError(TemplateError):
2 unmodified lines
39 rendering.40 """4142 def __init__(self, message, pos):55 super(TemplateRuntimeError, self).__init__(message)43 RuntimeError.__init__(self, message)44 self.pos = pos
modified:jinja/filters.py-7 removed
34 unmodified lines
35 """36 if count is None:37 return s.replace(old, new)38 return s.replace(old, new, count)39do_replace = stringfilter(do_replace)394041def do_upper(s):42 """
1 unmodified line
4445 Return a copy of s converted to uppercase.46 """47 return s.upper()49do_upper = stringfilter(do_upper)484950def do_lower(s):51 """
1 unmodified line
5354 Return a copy of s converted to lowercase.55 """56 return s.lower()59do_lower = stringfilter(do_lower)575859def do_escape(s, attribute=False):60 """
5 unmodified lines
66 s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")67 if attribute:68 s = s.replace('"', "&quot;")69 return s73do_escape = stringfilter(do_escape)707172def do_addslashes(s):73 """
1 unmodified line
7576 Adds slashes to s.77 """78 return s.encode('utf-8').encode('string-escape').decode('utf-8')83do_addslashes = stringfilter(do_addslashes)798081def do_capitalize(s):82 """
2 unmodified lines
85 Return a copy of the string s with only its first character86 capitalized.87 """88 return s.capitalize()94do_capitalize = stringfilter(do_capitalize)899091def do_title(s):92 """
2 unmodified lines
95 Return a titlecased version of s, i.e. words start with uppercase96 characters, all remaining cased characters have lowercase.97 """98 return s.title()105do_title = stringfilter(do_title)99100101def do_default(default_value=u''):102 """
94 unmodified lines
modified:jinja/lexer.py+1 added-1 removed
20 unmodified lines
21 '+', '-', '*', '/', '%',22 # braces and parenthesis23 '[', ']', '(', ')', '{', '}',24 # attribute access and comparison / logical operators25 '.', ',', '|', '==', '<', '>', '<=', '>=', '!=',25 '.', ':', ',', '|', '==', '<', '>', '<=', '>=', '!=', '=',26 ur'or\b', ur'and\b', ur'not\b'27]))2829
162 unmodified lines