所以,我想创建一个有关联模板的类。当我运行类的render()方法时,模板被处理并作为字符串返回。你知道吗
到目前为止,我的情况是:
class MyClass():
...
def render(self):
with open(self._template, O_RDONLY | O_NONBLOCK) as template_file:
html = template_file.read()
tpl = Template(html)
return tpl.render(self._template_variables)
但这会引发一个错误:
AttributeError: __exit__
我做错什么了?你知道吗
顺便说一句,如果有人有更好的建议来实施这个,我是开放的想法。你知道吗
我不知道为什么要复制django中提供的功能;但是如果必须,请使用^{} :
我之所以使用^{} ,是因为
render_to_string
方法采用模板名称,而您正在向它传递一个路径。你知道吗一般来说,避免硬编码,比如文件系统路径,因为它会降低代码的可移植性。你知道吗
with运算符使close()方法冗余
线路
不应该在
with
语句中调用,因为它的目的是自动释放资源。抛出AttributeError
是因为实际上,您要关闭文件两次。你知道吗相关问题 更多 >
编程相关推荐