# -*- coding: utf-8 -*-
from mako.lookup import TemplateLookup
mylookup = TemplateLookup(
directories='./mako_templates',
#module_directory='./mako_templates',
input_encoding='utf-8',
output_encoding='utf-8',
default_filters=['decode.utf8'],
)
mytemplate = mylookup.get_template('mytmpl.txt')
print mytemplate.render(x='0')
## mytmpl.txt
<%
if x == 0:
x = 1
%>
${x}
This works:
## mytmpl.txt
<%
y = x
%>
${y}
What am I missing? Is there something special about the if in Python
blocks?
Regards, Clodoaldo Pinto Neto
> ## mytmpl.txt
>
> <%
> if x == 0:
> x = 1
> %>
>
> ${x}
>
its normal python. youre assigning to "x", which means its local to
the function youre inside of. therefore you cant reference it
beforehand.
def somefunction():
if x == 0:
x = 1
somefunction()
will raise the same error.
Ok thanks. Now I found a work around it. But why this also does not work:?
## mytmpl.txt
<%
global x
if (x == 0):
x = 1
%>
${x}
Is the if inside his very own function?
Regards,
--
Clodoaldo Pinto Neto
> Ok thanks. Now I found a work around it. But why this also does not
> work:?
>
> ## mytmpl.txt
>
> <%
> global x
> if (x == 0):
> x = 1
> %>
>
> ${x}
>
> Is the if inside his very own function?
>
>>> def foo():
... global x
... if x == 0:
... x = 1
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in foo
NameError: global name 'x' is not defined
>>> x = 0
>>> def foo():
... global x
... if x == 0:
... x = 1
... return x
...
>>> foo()
1
Then how does that compares to:
print mytemplate.render(x=0)
<%
global x
if (x == 0):
x = 1
%>
${x}
> Then how does that compares to:
>
> print mytemplate.render(x=0)
>
> <%
> global x
> if (x == 0):
> x = 1
> %>
> ${x}
>
its the same thing. the "x" inside your context is not going to get
used because you have declared "x" explicitly.