Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load django template from the database

Im trying to render a django template from a database outside of djangos normal request-response structure. But it appears to be non-trivial due to the way django templates are compiled. I want to do something like this:

>>> s = Template.objects.get(pk = 123).content
>>> some_method_to_render(s, {'a' : 123, 'b' : 456})
>>> ... the rendered output here ...

How do you do this?

like image 989
Björn Lindqvist Avatar asked Mar 17 '10 14:03

Björn Lindqvist


2 Answers

There's nothing complicated about this, and it doesn't have anything to do with the request/response structure. All you need to do is pass the template string into the django.template.Template constructor (BTW, I've changed the name of your model, to avoid confusion):

from django.template import Context, Template
from myapp.models import DbTemplate

s = DbTemplate.objects.get(pk=123).content
tpl = Template(s)
tpl.render(Context(dict(a=123, b=456)))
like image 57
Daniel Roseman Avatar answered Nov 16 '22 01:11

Daniel Roseman


There is a reusable app which loads templates from the database:

http://django-dbtemplates.readthedocs.org/en/latest/

like image 41
guettli Avatar answered Nov 16 '22 02:11

guettli