如何将变量传递给自定义Django模板加载器?
我的字典里有模板,我想让我的模板加载器把它们取出来。但是,由于它是由Django代码实例化的,因此我无法将字典传递给它 将变量传递给模板加载器的正确方法是什么?(字典是动态生成的,因此我无法使用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):
字典
:
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
。谢谢你的帮助。