Skip to content
Myr

some more stuff for jinja2

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 fa865fb · Browse files · 6 files+161 added−24 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+161 added−24 removed

  • other:+161 added−24 removed

6 files+161 added−24 removed

modified:jinja2/compiler.py+4 added-4 removed
562 unmodified lines
563 arg_tuple))564 for arg in node.defaults:565 self.visit(arg)566 self.write(', ')567 self.write('), %r, %r)' % (568 macro_frame.accesses_arguments,569 macro_frame.accesses_caller567 self.write('), %s, %s)' % (568 macro_frame.accesses_arguments and '1' or '0',569 macro_frame.accesses_caller and '1' or '0'570 ))571572 def visit_CallBlock(self, node, frame):573 call_frame = self.function_scoping(node, frame)
6 unmodified lines
580 self.writeline('caller = Macro(call, None, (%s), (' % arg_tuple)581 for arg in node.defaults:582 self.visit(arg)583 self.write(', ')584 self.write('), %r, False)' % call_frame.accesses_arguments)584 self.write('), %s, 0)' % (call_frame.accesses_arguments and '1' or '0'))585 if frame.buffer is None:586 self.writeline('yield ', node)587 else:588 self.writeline('%s.append(' % frame.buffer, node)
280 unmodified lines
modified:jinja2/environment.py-1 removed
105 unmodified lines
106 if isinstance(source, basestring):107 source = self.parse(source, filename)108 node = optimize(source, self)109 source = generate(node, self, filename)110 print source110 if raw:111 return source112 if isinstance(filename, unicode):113 filename = filename.encode('utf-8')
40 unmodified lines
modified:jinja2/nodes.py+4 added-3 removed
387 unmodified lines
388class Filter(Expr):389 """{{ foo|bar|baz }}"""390 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')391392 def as_const(self):393 if self.node is None:392 def as_const(self, obj=None):393 if self.node is obj is None:394 raise Impossible()395 filter = self.environment.filters.get(self.name)396 if filter is None or getattr(filter, 'contextfilter', False):397 raise nodes.Impossible()398 if obj is None:398 obj = self.node.as_const()399 obj = self.node.as_const()400 args = [x.as_const() for x in self.args]401 kwargs = dict(x.as_const() for x in self.kwargs)402 if self.dyn_args is not None:403 try:
153 unmodified lines
modified:jinja2/optimizer.py+26 added
93 unmodified lines
94 return self.generic_visit(node, context)95 finally:96 context.pop()9798 def visit_FilterBlock(self, node, context):99 """Try to filter a block at compile time."""100 node = self.generic_visit(node, context)101 context.push()102103 # check if we can evaluate the wrapper body into a string104 # at compile time105 buffer = []106 for child in node.body:107 if not isinstance(child, nodes.Output):108 return node109 for item in child.optimized_nodes():110 if isinstance(item, nodes.Node):111 return node112 buffer.append(item)113114 # now check if we can evaluate the filter at compile time.115 try:116 data = node.filter.as_const(u''.join(buffer))117 except nodes.Impossible:118 return node119120 context.pop()121 const = nodes.Const(data, lineno=node.lineno)122 return nodes.Output([const], lineno=node.lineno)123124 def visit_For(self, node, context):125 """Loop unrolling for iterable constant values."""126 try:127 iterable = self.visit(node.iter, context).as_const()
114 unmodified lines
modified:bench.py+124 added-16 removed
1from jinja import Environment as E12from jinja2 import Environment as E23from mako.template import Template as M1from django.conf import settings2settings.configure()3from django.template import Template as DjangoTemplate, Context as DjangoContext4from jinja2 import Environment as JinjaEnvironment5from mako.template import Template as MakoTemplate6from timeit import Timer75t1, t2 = [e.from_string("""6<ul>7{%- for item in seq %}8 <li>{{ item|e }}</li>9{%- endfor %}10</ul>11""") for e in E1(), E2()]813m = M("""14<ul>15% for item in seq:16 <li>${item|h}</li>17% endfor18</ul>9jinja_template = JinjaEnvironment(10 line_statement_prefix='%',11 variable_start_string="${",12 variable_end_string="}"13).from_string("""\14<!doctype html>15<html>16 <head>17 <title>${page_title|e}18 </head>19 <body>20 <div class="header">21 <h1>${page_title|e}</h1>22 </div>23 <ul class="navigation">24 % for href, caption in [25 ('index.html', 'Index'),26 ('downloads.html', 'Downloads'),27 ('products.html', 'Products')28 ]29 <li><a href="${href|e}">${caption|e}</a></li>30 % endfor31 </ul>32 <div class="table">33 <table>34 % for row in table35 <tr>36 % for cell in row37 <td>${cell}</td>38 % endfor39 </tr>40 % endfor41 </table>42 </div>43 </body>44</html>\45""")4647django_template = DjangoTemplate("""\48<!doctype html>49<html>50 <head>51 <title>{{ page_title }}52 </head>53 <body>54 <div class="header">55 <h1>{{ page_title }}</h1>56 </div>57 <ul class="navigation">58 {% for href, caption in navigation %}59 <li><a href="{{ href }}">{{ caption }}</a></li>60 {% endfor %}61 </ul>62 <div class="table">63 <table>64 {% for row in table %}65 <tr>66 {% for cell in row %}67 <td>{{ cell }}</td>68 {% endfor %}69 </tr>70 {% endfor %}71 </table>72 </div>73 </body>74</html>\75""")7677mako_template = MakoTemplate("""\78<!doctype html>79<html>80 <head>81 <title>${page_title|h}82 </head>83 <body>84 <div class="header">85 <h1>${page_title|h}</h1>86 </div>87 <ul class="navigation">88 % for href, caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]:89 <li><a href="${href|h}">${caption|h}</a></li>90 % endfor91 </ul>92 <div class="table">93 <table>94 % for row in table:95 <tr>96 % for cell in row:97 <td>${cell}</td>98 % endfor99 </tr>100 % endfor101 </table>102 </div>103 </body>104</html>\105""")106107context = {108 'page_title': 'mitsuhiko\'s benchmark',109 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)]110}111112def test_jinja():113 jinja_template.render(context)114115def test_django():116 c = DjangoContext(context)117 c['navigation'] = [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]118 django_template.render(c)119120def test_mako():121 mako_template.render(**context)122123124for test in 'jinja', 'mako', 'django':125 t = Timer(setup='from __main__ import test_%s as bench' % test,126 stmt='bench()')127 print '%-20s%.4fms' % (test, t.timeit(number=20) / 20)
modified:test_filter_and_linestatements.py+3 added
14 unmodified lines
15 [${var}]16% endcall17% filter escape18 <hello world>19 % for item in [1, 2, 3]20 - ${item}21 % endfor22% endfilter23""")2425print tmpl.render(seq=range(10))