Getting python Cheetah to print backslash

162 views Asked by At

I am having trouble getting the Python Cheetah to print a backslash for me.

Cheetah version 2.4.4

from Cheetah.Template import Template

my_template = """
Stuff $var1\\$var2
"""

t = Template(source=my_template, searchList = [{"var1" : """\\x\y\z""", "var2" : "some"}])
print str(t)

I expected to see the output

Stuff \\x\y\z\some

But I get

Stuff \x\y\z$var2

What should the template be in this case?

2

There are 2 answers

0
Kannan Ekanath On BEST ANSWER

An easy way to get this working is to use the cheetah <%= => syntax

my_template = """
Stuff $var1<%= '\\\\'%>$var2
"""
0
phd On

The problem with the code

my_template = """
Stuff $var1\\$var2
"""

is that first it's parsed by Python; Python interprets doubled backslashes and converts them to single backslashes: my_template becomes Stuff $var1\$var2 and that what's passed to Template. If you want doubled backslashes you have to double them once more or use Python raw string. Either

my_template = """
Stuff $var1\\\\$var2
"""

or

my_template = r"""
Stuff $var1\\$var2
"""