Python模板类

2024-04-20 05:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我想创建一个有关联模板的类。当我运行类的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__

我做错什么了?你知道吗

顺便说一句,如果有人有更好的建议来实施这个,我是开放的想法。你知道吗


Tags: 方法字符串self模板defhtmlwithmyclass
3条回答

我不知道为什么要复制django中提供的功能;但是如果必须,请使用^{}

import os
from django.template.loader import render_to_string

class FooClass(object):
    def render(self):
       return render_to_string(os.path.basename(self._template),
                               self._template_variables)

我之所以使用^{},是因为render_to_string方法采用模板名称,而您正在向它传递一个路径。你知道吗

一般来说,避免硬编码,比如文件系统路径,因为它会降低代码的可移植性。你知道吗

with运算符使close()方法冗余

线路

template_file.close()

不应该在with语句中调用,因为它的目的是自动释放资源。抛出AttributeError是因为实际上,您要关闭文件两次。你知道吗

相关问题 更多 >