Using external URLs in Django's TEMPLATE_DIRS

后端 未结 3 1506
野性不改
野性不改 2020-12-30 13:10

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

Because of this, when I call

get_template(\'some/template.html\')
3条回答
  •  余生分开走
    2020-12-30 13:44

    You can't do this.

    It has nothing to do with path names. It's just that the filesystem template loader needs to load things from the filesystem, hence the name.

    This is completely different from the case of MEDIA_URL: that simply adds a path into your HTML, which your browser then loads. Django doesn't care where that file lives: although in fact the opposite applies, in that if you pass it a filepath that isn't a URL (ie served by a webserver somewhere), it simply won't work.

    Now, you could write a template loader that gets its templates from another server. Template loaders are pluggable - you just need to put the name of your new loader in the TEMPLATE_LOADERS setting. The loader itself would need to use something like urllib.urlopen to get the template from the external server.

    But think very carefully before you do this. This means that every single template request now requires a call to an external server before you can serve the page. In the typical case of a template that extends other templates and includes calls to included template tags, that might be five or ten calls. And, unlike media files, it can't be done in parallel: the page simply won't be served until the whole process is finished. This is likely to make your webserver very very slow.

    I don't know why you think you need to do this. Templates are part of your application code, so they would normally live on the same server as your Python code. If you really have some reason to keep them externally, one solution might be to mount the external filesystem onto your webserver via something like sshfs. It's still likely to be very slow though. Think again.

提交回复
热议问题