[svn] implemented filter directive
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 cb654fb · Browse files · 3 files·+133 added−40 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+133 added−40 removed
- other:+133 added−40 removed
Provenance
- Commit
20eacb7- Tree
03249a2- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
cb654fb
3 files changed+133 added−40 removed
modified:jinja/translators/python.py+71 added-38 removed
84 unmodified lines85 nodes.IfCondition: self.handle_if_condition,86 nodes.Cycle: self.handle_cycle,87 nodes.Print: self.handle_print,88 nodes.Macro: self.handle_macro,89+ nodes.Filter: self.handle_filter,90 nodes.Block: self.handle_block,91+ nodes.Include: self.handle_include,92 # used python nodes93 ast.Name: self.handle_name,94 ast.AssName: self.handle_name,95 ast.Compare: self.handle_compare,47 unmodified lines143 Indent the current text.144 """145 return (' ' * (self.indention * 4)) + text146 147+ def filter(self, s, filter_nodes):148+ """149+ Apply a filter on an object.150+ """151+ filters = []152+ for n in filter_nodes:153+ if n.__class__ is ast.CallFunc:154+ if n.node.__class__ is not ast.Name:155+ raise TemplateSyntaxError('invalid filter. filter must '156+ 'be a hardcoded function name '157+ 'from the filter namespace',158+ n.lineno)159+ args = []160+ for arg in n.args:161+ if arg.__class__ is ast.Keyword:162+ raise TemplateSyntaxError('keyword arguments for '163+ 'filters are not supported.',164+ n.lineno)165+ args.append(self.handle_node(arg))166+ if n.star_args is not None or n.dstar_args is not None:167+ raise TemplateSynaxError('*args / **kwargs is not supported '168+ 'for filters', n.lineno)169+ filters.append('(%r, %s)' % (170+ n.node.name,171+ _to_tuple(args)172+ ))173+ elif n.__class__ is ast.Name:174+ filters.append('(%r, ())' % n.name)175+ else:176+ raise TemplateSyntaxError('invalid filter. filter must be a '177+ 'hardcoded function name from the '178+ 'filter namespace',179+ n.lineno)180+ return 'apply_filters(%s, context, %s)' % (s, _to_tuple(filters))181+182 def handle_node(self, node):183 """184 Handle one node185 """36 unmodified lines222 ' perform_test = environment.perform_test\n'223 ' apply_filters = environment.apply_filters\n'224 ' call_function = environment.call_function\n'225 ' call_function_simple = environment.call_function_simple\n'189- ' finish_var = environment.finish_var\n'190- ' write_var = lambda x: write(finish_var(x))\n\n'226+ ' finish_var = environment.finish_var\n\n'227 ' # TEMPLATE CODE'228 ]229 self.indention += 1230 lines.append(self.handle_node_list(node))108 unmodified lines339 hardcoded = False340 self.indention -= 1341 342 if hardcoded:307- write('write_var(context.current[%r].cycle())' % name)343+ write('write(finish_var(context.current[%r].cycle()))' % name)344 else:309- write('write_var(context.current[%r].cycle(%s))' % (345+ write('write(finish_var(context.current[%r].cycle(%s)))' % (346 name,347 self.handle_node(node.seq)348 ))349 2 unmodified lines352 def handle_print(self, node):353 """354 Handle a print statement.355 """320- return self.indent('write_var(%s)' % self.handle_node(node.variable))356+ return self.indent('write(finish_var(%s))' % self.handle_node(node.variable))357 358 def handle_macro(self, node):359 """360 Handle macro declarations.13 unmodified lines374 buf.append(self.indent('context[%r] = macro' % node.name))375 376 return '\n'.join(buf)377 378+ def handle_filter(self, node):379+ """380+ Handle filter sections.381+ """382+ buf = []383+ write = lambda x: buf.append(self.indent(x))384+ write('def filtered():')385+ self.indention += 1386+ write('context.push()')387+ write('buffer = []')388+ write('write = buffer.append')389+ buf.append(self.handle_node(node.body))390+ write('context.pop()')391+ write('return u\'\'.join(buffer)')392+ self.indention -= 1393+ write('write(%s)' % self.filter('filtered()', node.filters))394+ return '\n'.join(buf)395+396 def handle_block(self, node):397 """398 Handle blocks in the sourcecode. We only use them to399 call the current block implementation that is stored somewhere18 unmodified lines418 write('context.pop()')419 buf.append(self.indent('# END OF BLOCK'))420 return '\n'.join(buf)421 422+ def handle_include(self, node):423+ """424+ Include another template at the current position.425+ """426+ buf = [self.indent('# INCLUDED TEMPLATE %r' % node.filename)]427+ tmpl = self.environment.loader.parse(node.template,428+ node.filename)429+ buf.append(self.handle_node(tmpl))430+ buf.append(self.indent('# END OF INCLUSION'))431+ return '\n'.join(buf)432+433 # -- python nodes434 435 def handle_name(self, node):436 """98 unmodified lines535 def handle_bitor(self, node):536 """537 We use the pipe operator for filtering.538 """474- filters = []475- for n in node.nodes[1:]:476- if n.__class__ is ast.CallFunc:477- if n.node.__class__ is not ast.Name:478- raise TemplateSyntaxError('invalid filter. filter must '479- 'be a hardcoded function name '480- 'from the filter namespace',481- n.lineno)482- args = []483- for arg in n.args:484- if arg.__class__ is ast.Keyword:485- raise TemplateSyntaxError('keyword arguments for '486- 'filters are not supported.',487- n.lineno)488- args.append(self.handle_node(arg))489- if n.star_args is not None or n.dstar_args is not None:490- raise TemplateSynaxError('*args / **kwargs is not supported '491- 'for filters', n.lineno)492- filters.append('(%r, %s)' % (493- n.node.name,494- _to_tuple(args)495- ))496- elif n.__class__ is ast.Name:497- filters.append('(%r, ())' % n.name)498- else:499- raise TemplateSyntaxError('invalid filter. filter must be a '500- 'hardcoded function name from the '501- 'filter namespace',502- n.lineno)503- return 'apply_filters(%s, context, %s)' % (504- self.handle_node(node.nodes[0]),505- _to_tuple(filters)506- )539+ return self.filter(self.handle_node(node.nodes[0]), node.nodes[1:])540 541 def handle_call_func(self, node):542 """543 Handle function calls.165 unmodified linesmodified:jinja/nodes.py+39 added
201 unmodified lines202 self.body203 )204 205 206+class Filter(Node):207+ """208+ Node for filter sections.209+ """210+211+ def __init__(self, lineno, body, filters):212+ self.lineno = lineno213+ self.body = body214+ self.filters = filters215+216+ def get_items(self):217+ return [self.body, self.filters]218+219+ def __repr__(self):220+ return 'Filter(%r)' % (221+ self.body,222+ self.filters223+ )224+225+226 class Block(Node):227 """228 A node that represents a block.229 """28 unmodified lines258 def __init__(self, lineno, template):259 self.lineno = lineno260 self.template = template261 262+ def get_items(self):263+ return [self.template]264+265 def __repr__(self):266 return 'Extends(%r)' % self.template267+268+269+class Include(Node):270+ """271+ A node that represents the include tag.272+ """273+274+ def __init__(self, lineno, template):275+ self.lineno = lineno276+ self.template = template277+278+ def get_items(self):279+ return [self.template]280+281+ def __repr__(self):282+ return 'Include(%r)' % self.templatemodified:jinja/parser.py+23 added-2 removed
21 unmodified lines22 switch_for = lambda p, t, d: t == 'name' and d in ('else', 'endfor')23 end_of_for = lambda p, t, d: t == 'name' and d == 'endfor'24 switch_if = lambda p, t, d: t == 'name' and d in ('else', 'elif', 'endif')25 end_of_if = lambda p, t, d: t == 'name' and d == 'endif'26+end_of_filter = lambda p, t, d: t == 'name' and d == 'endfilter'27 end_of_macro = lambda p, t, d: t == 'name' and d == 'endmacro'28 end_of_block_tag = lambda p, t, d: t == 'name' and d == 'endblock'29 30 18 unmodified lines49 self.directives = {50 'for': self.handle_for_directive,51 'if': self.handle_if_directive,52 'cycle': self.handle_cycle_directive,53+ 'filter': self.handle_filter_directive,54 'print': self.handle_print_directive,55 'macro': self.handle_macro_directive,56 'block': self.handle_block_directive,55- 'extends': self.handle_extends_directive57+ 'extends': self.handle_extends_directive,58+ 'include': self.handle_include_directive59 }60 61 def handle_for_directive(self, lineno, gen):62 """61 unmodified lines124 # ast is something like Discard(CallFunc(Name('_cycle'), ...))125 # skip that.126 return nodes.Cycle(lineno, ast.expr.args[0])127 128+ def handle_filter_directive(self, lineno, gen):129+ """130+ Handle {% filter foo|bar %} directives.131+ """132+ ast = self.parse_python(lineno, gen, '_filter(dummy|%s)')133+ body = self.subparse(end_of_filter, True)134+ self.close_remaining_block()135+ return nodes.Filter(lineno, body, ast.expr.args[0].nodes[1:])136+137 def handle_print_directive(self, lineno, gen):138 """139 Handle {{ foo }} and {% print foo %}.140 """56 unmodified lines197 return rv198 199 def handle_extends_directive(self, lineno, gen):200 """189- Handle extends directive used for inheritance.201+ Handle the extends directive used for inheritance.202 """203 tokens = list(gen)204 if len(tokens) != 1 or tokens[0][1] != 'string':205 raise TemplateSyntaxError('extends requires a string', lineno)206 if self.extends is not None:207 raise TemplateSyntaxError('extends called twice', lineno)208 self.extends = nodes.Extends(lineno, tokens[0][2][1:-1])209 210+ def handle_include_directive(self, lineno, gen):211+ """212+ Handle the include directive used for template inclusion.213+ """214+ tokens = list(gen)215+ if len(tokens) != 1 or tokens[0][1] != 'string':216+ raise TemplateSyntaxError('include requires a string', lineno)217+ return nodes.Include(lineno, tokens[0][2][1:-1])218+219 def parse_python(self, lineno, gen, template='%s'):220 """221 Convert the passed generator into a flat string representing222 python sourcecode and return an ast node or raise a115 unmodified lines