Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using external URLs in Django's TEMPLATE_DIRS

Django's TEMPLATE_DIRS in Settings.py calls for unix style slashes.

Because of this, when I call

get_template('some/template.html')

in a view, the result always starts at the root, and results in a call to

/home/username/projectname/public/some/template.html

The problem is that I'd like to use templates hosted on an entirely different site. This works fine for other Settings.py fields (MEDIA_URL and STATIC_URL), where it will take an absolute http path with no objection.

Given an http path,

 TEMPLATE_DIRS ('http://example.com/',)

in Settings.py will force

get_template('some/template.html')

in a view to try and find

/home/username/projectname/public/http://example.com/some/template.html

I've tried to circumvent this like so

TEMPLATE_DIRS ('../../../../http://example.com/',)

But it still forces a leading slash, so I get "/http://example.com", which is useless.

My questions:

  1. Is there a way to trick this into pulling the template files from another server?
  2. Is that even feasible, given that the template files need to be processed for the view?
  3. Is it possible to create an alternate to 'django.template.loaders.filesystem.Loader' that doesn't call for unix style slashes?
like image 907
LiveMethod Avatar asked Nov 20 '11 11:11

LiveMethod


1 Answers

You don't need to use the template directory is you dont want to. If you have a server that is serving template files, you can simply fetch them remotely using urllib2 and create and render the template with a context manually:

import urllib2
from django.template import Context, Template

tpl_html = urllib2.urlopen("http://mysite.com")
tpl = Template(tpl_html)
return tpl.render(Context({
    'some_variable' : 'some_val',
})

If you are going to do this, you have to incorporate some caching, as for every request to using this template, you need to make an external request. Alternatively you could write this into a custom loader but it will suffer the same limitations.

like image 180
Timmy O'Mahony Avatar answered Sep 21 '22 17:09

Timmy O'Mahony