Extending templates programmatically

96 views
Skip to first unread message

Ian Clelland

unread,
Apr 16, 2006, 6:11:51 PM4/16/06
to django-d...@googlegroups.com
I've been looking into the django template system, and how to use it
in situations other than html rendering (e.g, building up email
messages from templates in the database)

It would be very useful in these sorts of situations to be able to
extend from a template that does not exist inside of a template
directory on the filesystem; for instance, template source from the
database, or from a string generated in python code.

(This issue was also mentioned a couple of days ago on the users list,
here: http://groups.google.com/group/django-users/browse_thread/thread/aea7d78cebbfe2d/ef0c805c653c4f70
)

The solution I've come up with is a 2-line patch to get_parent in
/templates/loader_tags.py which checks whether the parent variable
pulled from context is already a Template object, and if it is, just
return that, rather than trying to load it.

Now I can do things like this:

from django.template import Context, Template, loader
a = Template("{% extends templateone %}{% block one %}Hello {{ name
}}{% endblock %}")
b = Template("<h1>{% block one %}Stuff{% endblock %}</h1>")
a.render(Context({'name': 'world', 'templateone': b}))

which returns "<h1>Hello world</h1>"

Is this patch worth submitting an enhancement ticket? Or have I
managed to miss a simpler way of doing this?

Regards,
Ian Clelland
<clel...@gmail.com>

Adrian Holovaty

unread,
Apr 16, 2006, 8:59:15 PM4/16/06
to django-d...@googlegroups.com
On 4/16/06, Ian Clelland <clel...@gmail.com> wrote:
> Now I can do things like this:
>
> from django.template import Context, Template, loader
> a = Template("{% extends templateone %}{% block one %}Hello {{ name
> }}{% endblock %}")
> b = Template("<h1>{% block one %}Stuff{% endblock %}</h1>")
> a.render(Context({'name': 'world', 'templateone': b}))
>
> which returns "<h1>Hello world</h1>"
>
> Is this patch worth submitting an enhancement ticket? Or have I
> managed to miss a simpler way of doing this?

Sure, I'd say that's worth submitting as an enhancement ticket. I can
definitely see use for that!

Adrian

--
Adrian Holovaty
holovaty.com | djangoproject.com

Ian Clelland

unread,
Apr 17, 2006, 6:54:48 AM4/17/06
to django-d...@googlegroups.com
On 4/16/06, Adrian Holovaty <holo...@gmail.com> wrote:
>
> Sure, I'd say that's worth submitting as an enhancement ticket. I can
> definitely see use for that!

Done -- it's at http://code.djangoproject.com/ticket/1650

(It's a bit more than two lines, but only because I threw in a couple
of unit tests and a line of documentation.)


Ian Clelland
<clel...@gmail.com>

Reply all
Reply to author
Forward
0 new messages