Jibin
Jibin

Reputation: 3102

python how to convert from string.template object to string

This is very simple.I am sure I am missing something silly.

fp = open(r'D:\UserManagement\invitationTemplate.html', 'rb')        
html = Template(fp.read())
fp.close()
html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')
print html 

When i run this code in intepreter directly,I get the proper output. But when I run it from a file.I get <string.Template object at 0x012D33B0>.How do I convert from string.Template object to string.I have tried str(html).By the bye wasn't print statement supposed to do that(string conversion) ?

Upvotes: 18

Views: 13737

Answers (3)

wutz
wutz

Reputation: 3274

safe_substitute returns, as a string, the template with the substitutions made. This way, you can reuse the same template for multiple substitutions. So your code has to be

print html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')

Upvotes: 19

Pengman
Pengman

Reputation: 708

According to the docs you should take the return Value of safe_substitute

fp = open(r'D:\UserManagement\invitationTemplate.html', 'rb')        
html = Template(fp.read())
fp.close()
result = html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')
print result 

Upvotes: 5

HYRY
HYRY

Reputation: 97271

the result is returned by safe_substitute method:

result = html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')
print result

Upvotes: 2

Related Questions