moved example code around
[jinja2.git] / examples / profile.py
1 try:
2     from cProfile import Profile
3 except ImportError:
4     from profile import Profile
5 from pstats import Stats
6 from jinja2 import Environment as JinjaEnvironment
7
8 context = {
9     'page_title': 'mitsuhiko\'s benchmark',
10     '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)]
11 }
12
13 jinja_template = JinjaEnvironment(
14     line_statement_prefix='%',
15     variable_start_string="${",
16     variable_end_string="}"
17 ).from_string("""\
18 <!doctype html>
19 <html>
20   <head>
21     <title>${page_title|e}</title>
22   </head>
23   <body>
24     <div class="header">
25       <h1>${page_title|e}</h1>
26     </div>
27     <ul class="navigation">
28     % for href, caption in [
29         ('index.html', 'Index'),
30         ('downloads.html', 'Downloads'),
31         ('products.html', 'Products')
32       ]
33       <li><a href="${href|e}">${caption|e}</a></li>
34     % endfor
35     </ul>
36     <div class="table">
37       <table>
38       % for row in table
39         <tr>
40         % for cell in row
41           <td>${cell}</td>
42         % endfor
43         </tr>
44       % endfor
45       </table>
46     </div>
47   </body>
48 </html>\
49 """)
50
51
52 p = Profile()
53 p.runcall(lambda: jinja_template.render(context))
54 stats = Stats(p)
55 stats.sort_stats('time', 'calls')
56 stats.print_stats()