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
- Form field with fixed value by roam 1 week, 4 days ago
- New Snippet! by Antoliny0919 2 weeks, 3 days ago
- Add Toggle Switch Widget to Django Forms by OgliariNatan 3 months, 1 week ago
- get_object_or_none by azwdevops 6 months, 4 weeks ago
- Mask sensitive data from logger by agusmakmun 8 months, 3 weeks 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.