我有一个类,它采用任意HTML模板,str.format()
用于特定用例。例如:
<h1>Hi, {userName}!</h1>
<p> It's {weather} today.</p>
会变成:
<h1>Hi, Jon Skeet!</h1>
<p>It's sunny today.</p>
要做到这一点,我有一个Template
类:
class Template:
def __init__(self, name, **kwargs):
templateDirectory = getTemplateDirectory() # we don't need to worry about this
with open(os.path.join(templateDirectory, "templates", name + ".html")) as templateFile: # we get the template we need
self.template = templateFile.read()
print(self.template) # all in order: we get the un-formatted HTML
print(kwargs) # all in order: we get a dict of things to replace (i.e. {'userName': 'Jon Skeet', 'weather': 'sunny'} )
self.final = self.template.format(**kwargs) # this should just replace things nicely, but it doesn't: why?
def __str__(self):
return self.final
我实例化如下:
ErrorTemplate = Template('foo', var1=42, var2='foo')
print(str(ErrorTemplate))
我得到的错误如下:
Traceback (most recent call last):
File "/path/to/file.py", line 11, in <module>
ErrorTemplate = Template('foo', var1=42, var2='bar')
File "/path/to/the/file/with/Template/class.py", line 10, in __init__
self.final = self.template.format(**kwargs)
KeyError: 'document'
我没有使用&#39;文件&#39;任何地方。我不知道它到底在哪里&#39;记录&#39;从。我做错了什么?