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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
indeed, very useful!
#
Yeah, useful while living in fantASCII land: then you realize you need codecs.open instead. ;-)
#
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.