jinja arbitrary code expressions?

Neal Becker ndbecker2 at gmail.com
Wed Apr 29 21:34:27 EDT 2009


Neal Becker wrote:

> Can jinja templates contain arbitrary python code?
> 
> In mako, I could do (for example):
> --------
> from mako.template import Template
> 
> mytemplate = Template('''
> <%!
>     from math import sin, pi
> %>
> hello ${name}!
> ${x}**2 = ${x**2}
> % for i in xrange (10):
> w[${i}] = ${sin (pi/4*i)}
> % endfor
> ''')
> d = {'name' : 'Neal',
>      'x' : 10
>      }
> print mytemplate.render(**d)
> --------
> 
> Could I do something similar in jinja? (import code, call arbitrary
> functions...)
> 

I see this will work:

from jinja2 import Template

import math

template = Template ('''
print {{ w }}
{% for x in range (10) %} # test
print w[{{ x }}]
print w[{{ x**2 }}]
sin(pi/4*{{x}}) = {{math.sin(math.sin(math.pi/4*x))}}
{% endfor %}
''')

d = {
    'w' : 'hello',
    'math' : math,
    }
t = template.render(d)







More information about the Python-list mailing list