Login

Render to file

Author:
jacobian
Posted:
April 8, 2008
Language:
Python
Version:
.96
Tags:
template render file
Score:
4 (after 4 ratings)

As a demo, I was asked to write a render_to_file() function to load a template and render it to a file. Turns out it's amazingly easy, and I think it's a neat trick to have in your bag of tools.

1
2
3
4
from django.template.loader import render_to_string

def render_to_file(template, filename, context):
    open(filename, "w").write(render_to_string(template, context))

More like this

Comments

jezdez (on April 9, 2008):
<p>indeed, very useful!</p>

#

tekNico (on April 12, 2008):
<p>Yeah, useful while living in fantASCII land: then you realize you need codecs.open instead. ;-)</p>

#

davmuz (on July 31, 2012):
<p>The Django template engine renders as UTF-8, so you have to write a UTF-8 file.</p> <p>``import codecs</p> <p>codecs.open(filename, 'w', 'utf-8').write(render_to_string(template, context))``</p>

#

Please login first before commenting.