传递请求到自定义Django模板加载器 [英] Passing request to custom Django template loader

查看:99
本文介绍了传递请求到自定义Django模板加载器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的Django应用程序编写自定义模板加载程序,该应用程序基于作为请求的一部分的键查找特定的文件夹。

I want to write custom template loader for my Django app which looks for a specific folder based on a key that is part of the request.

让我进一步了解更多细节。假设我将获得每个请求的密钥(我使用中间件填充)。

Let me get into more details to be clear. Assume that I will be getting a key on every request(which I populate using a middleware).

示例:request.key可以是india或usa或uk。

Example: request.key could be 'india' or 'usa' or 'uk'.

我希望我的模板加载程序查找模板 templates /< key> /< template.html> 。所以当我说 {%includehome.html%} 时,我想让模板加载器加载templates / india / home.html或templates / usa / home.html或templates / uk / home.html。

I want my template loader to look for the template "templates/<key>/<template.html>". So when I say {% include "home.html" %}, I want the template loader to load "templates/india/home.html" or "templates/usa/home.html" or "templates/uk/home.html" based on the request.

有没有办法将请求对象传递给自定义模板加载器?

Is there a way to pass the request object to a custom template loader?

推荐答案

我一直在寻找相同的解决方案,经过几天的搜索,决定使用thread.local()。在HTTP请求处理期间,简单地使请求对象全局化!

I've been searching for the same solution and, after a couple days of searching, decided to use threading.local(). Simply make the request object global for the duration of the HTTP request processing! Commence rotten tomato throwing from the gallery.

让我解释一下:

As的Django 1.8(根据开发版本docs),所有模板查找功能的dirs参数将被废弃。 (ref)

As of Django 1.8 (according to the development version docs) the "dirs" argument for all template finding functions will be deprecated. (ref)

这意味着没有参数传递到自定义模板加载器中,而不是正在请求的模板名称和模板目录列表。如果您要访问请求URL(或甚至会话信息)中的参数,则必须触及到其他存储机制中。

This means that there are no arguments passed into a custom template loader other than the template name being requested and the list of template directories. If you want to access paramters in the request URL (or even the session information) you'll have to "reach out" into some other storage mechanism.

import threading
_local = threading.local()

class CustomMiddleware:

    def process_request(self, request):
         _local.request = request

def load_template_source(template_name, template_dirs=None):
    if _local.request:
        # Get the request URL and work your magic here!
        pass

在我的情况下,我不是请求对象(直接)而是应该渲染哪个站点(我正在开发SaaS解决方案)模板。

In my case it wasn't the request object (directly) I was after but rather what site (I'm developing a SaaS solution) the template should be rendered for.

这篇关于传递请求到自定义Django模板加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆