PythonPower
PythonPower

Reputation:

AppEngine and Django: including a template file

As the title suggests, I'm using Google App Engine and Django.

I have quite a bit of identical code across my templates and would like to reduce this by including template files. So, in my main application directory I have the python handler file, the main template, and the template I want to include in my main template.

I would have thought that including {% include "fileToInclude.html" %} would work on its own but that simply doesn't include anything. I assume I have to set something up, maybe using TEMPLATE_DIRS, but can't figure it out on my own.

EDIT:

I've tried:

TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'), )

But to no avail. I'll try some other possibilities too.

Upvotes: 4

Views: 2750

Answers (4)

John Clarke Mills
John Clarke Mills

Reputation: 954

I am having the same problem and tracked it down into the ext.webapp package. In template.py, you'll find this comment on line 33:

Django uses a global setting for the directory in which it looks for templates. This is not natural in the context of the webapp module, so our load method takes in a complete template path, and we set these settings on the fly automatically. Because we have to set and use a global setting on every method call, this module is not thread safe, though that is not an issue for applications.

See line 92 in the same file. You can see the template dirs being squashed:

directory, file_name = os.path.split(abspath)
new_settings = {
    'TEMPLATE_DIRS': (directory,),
    'TEMPLATE_DEBUG': debug,
    'DEBUG': debug,
    }

UPDATE: Here is the workaround which worked for me - http://groups.google.com/group/google-appengine/browse_thread/thread/c3e0e4c47e4f3680/262b517a723454b6?lnk=gst&q=template_dirs#262b517a723454b6

Upvotes: 1

masher
masher

Reputation: 1

I've done the following to get around using includes:

def render(file, map={}):
  return template.render(
    os.path.join(os.path.dirname(__file__), '../templates', file), map)  

table = render("table.html", {"headers": headers, "rows": rows})   
final = render("final.html", {"table": table})

self.response.out.write(final)

Upvotes: 0

PythonPower
PythonPower

Reputation:

I found that it works "out of the box" if I don't load Templates first and render them with a Context object. Instead, I use the standard method shown in the AppEngine tutorial.

Upvotes: 1

Eli Courtwright
Eli Courtwright

Reputation: 192921

First, you should consider using template inheritance rather than the include tag, which is often appropriate but sometimes far inferior to template inheritance.

Unfortunately, I have no experience with App Engine, but from my experience with regular Django, I can tell you that you need to set your TEMPLATE_DIRS list to include the folder from which you want to include a template, as you indicated.

Upvotes: 3

Related Questions