Login

Render to file

Author:
jacobian
Posted:
April 8, 2008
Language:
Python
Version:
.96
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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

jezdez (on April 9, 2008):

indeed, very useful!

#

tekNico (on April 12, 2008):

Yeah, useful while living in fantASCII land: then you realize you need codecs.open instead. ;-)

#

davmuz (on July 31, 2012):

The Django template engine renders as UTF-8, so you have to write a UTF-8 file.

``import codecs

codecs.open(filename, 'w', 'utf-8').write(render_to_string(template, context))``

#

Please login first before commenting.