Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Template extend another one?

I've got some templates which I'm building from some data I've got stored in my DB:

my_template = Template(string_data)

Now I want that template to extend another one (also stored as text in the DB). How can I do that? Looking for something like:

my_template.base = other_template

Or whatever the syntax is. Can't find documentation on this.


I see template.nodelist in the source; can I maybe prepend some kind of extends node?


Added a bounty... will grant to first person who can tell me how to do this without hacking the core of django.

like image 261
mpen Avatar asked Oct 19 '25 03:10

mpen


1 Answers

No need to hack the core of Django. Creating your own template loader, as Ignacio recommends, is pretty simple. You just need to subclass django.template.loader.BaseLoader, and implement the load_template_source method. This just takes a string for the template name, which you can simply use to look up the item in the database and return the string.

In your case, since you've got two template elements in the the single db row, you might want to do something to specify it in the extends tag:

{% extends "myinstance.html_version" %}

and simply split that in load_template_source:

def load_template_source(self, template_name, template_dirs=None):
    name, field = template_name.split('.')
    tpl = TemplateModel.objects.get(name=name)
    return getattr(tpl, field)

Of course you'd want to put some error handling in there, but you get the idea. You just then specify this template loader in your settings TEMPLATE_LOADERS tuple.

Edit after comment I still don't really understand why, but if all you want to do is to choose the template to extend from dynamically, why not just insert that in the text template before processing?

    tpl_string = get_template_from_wherever()
    extender = '{% extends "%s" %}' % template_name_to_extend
    tpl = Template(extender + tpl_string)

Still a hack, but probably much less of one than mucking about with the internals of template inheritance.

like image 129
Daniel Roseman Avatar answered Oct 21 '25 18:10

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!