Login

Make anything into a template

Author:
realmac
Posted:
February 6, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

This is a quick and dirty way to reuse the Django templating system for your own ends. Just pop in the familiar Django template syntax into whatever content you like and any chunk of content can be a template. This is great if you need to wrap data in HTML (as in for a mass email). The best part about this is that your "template" can now be stored in a database, instead of just in the file system.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#views.py
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext, Context, Template
from models import DocumentTemplate
from django.utils.safestring import mark_safe

def printable_form(self, object_id, template_id):
    """Get a `template` and drop information into it."""
    doc_template = DocumentTemplate.objects.get(pk=template_id)
    result = get_object_or_404(SomeInfo, pk=object_id)
    t = Template(doc_template.content)
    c = Context({'result': result,})
    final_html = t.render(c)
    final_html = mark_safe(final_html)
    return render_to_response('printable.html', {'final_html':final_html}, RequestContext(request))

More like this

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

Comments

Please login first before commenting.