Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将变量传递给自定义Django模板加载器?_Django_Django Templates - Fatal编程技术网

如何将变量传递给自定义Django模板加载器?

如何将变量传递给自定义Django模板加载器?,django,django-templates,Django,Django Templates,我的字典里有模板,我想让我的模板加载器把它们取出来。但是,由于它是由Django代码实例化的,因此我无法将字典传递给它 将变量传递给模板加载器的正确方法是什么?(字典是动态生成的,因此我无法使用Django设置文件。) 我的加载程序代码,我还不能使用字典: class Loader(BaseLoader): is_usable = True def load_template_source(self, template_name, template_dirs=None):

我的字典里有模板,我想让我的模板加载器把它们取出来。但是,由于它是由Django代码实例化的,因此我无法将字典传递给它

将变量传递给模板加载器的正确方法是什么?(字典是动态生成的,因此我无法使用Django设置文件。)

我的加载程序代码,我还不能使用
字典

class Loader(BaseLoader):
    is_usable = True

    def load_template_source(self, template_name, template_dirs=None):
        if template_name in dictionary:
            return (dictionary[template_name],template_name)
        raise TemplateDoesNotExist("Could not find template '%s'." % template_name)

    load_template_source.is_usable = True

有什么问题吗?这应该行得通

只需在某个地方定义
字典

dictionary = {'template_name' : 'template content'}

class Loader(BaseLoader):
    is_usable = True

    def load_template_source(self, template_name, template_dirs=None):
        if template_name in dictionary:
            return (dictionary[template_name],template_name)
        raise TemplateDoesNotExist("Could not find template '%s'." % template_name)
如果它需要是动态的,则加入一个填充
字典的函数

class Loader(BaseLoader):
    is_usable = True

    def load_template_source(self, template_name, template_dirs=None):
        if template_name in self.get_dictionary():
            return (dictionary[template_name],template_name)
        raise TemplateDoesNotExist("Could not find template '%s'." % template_name)

    def get_dictionary(self):
         dynamic = {}
         # magically dynamically populate the dictionary
         return dynamic

我必须在另一个函数中填充字典,我忘记在分配给它之前添加
global dictionary
。谢谢你的帮助。