Web.py的模板系统很重要, 可以说是必备武器.
承接上一篇文档的代码.
按照web.py的官方文档说明开始做吧:
1. 在test目录下建立一个tmplt文件夹;
2. 在tmplt文件夹下建立一个模板文件t1.html
3. code2.py里增加代码
|
…… render = web.template.render('/tmplt/') …..
class hello: def GET(self): return render.t1(todos) #return "Hello, world!" 这句话注掉了,我们开始用模板了 …… |
4. 重启一下Apache(必备步骤,改动了py文件后,就要重启一下Apache,以使改动生效)
5. 地址栏里输入网址http://127.0.0.1/test2;
结果返回了HTTP 500 内部服务器错误. 查看C:\Program Files\Apache Software Foundation\Apache2.2\logs\error.log, 错误信息如下
|
Traceback (most recent call last): File :\\Python27\\lib\\site-packages\\web\\application.py", line 239, in process return self.handle() File :\\Python27\\lib\\site-packages\\web\\application.py", line 230, in handle return self._delegate(, self.fvars, args) File :\\Python27\\lib\\site-packages\\web\\application.py", line 462, in _delegate return handle_class(cls) File :\\Python27\\lib\\site-packages\\web\\application.py", line 438, in handle_class return tocall(*args) File "D:/SW_Code/test/code2.py", line 45, in GET return render.(todos) File :\\Python27\\lib\\site-packages\\web\\template.py", line 1016, in __getattr__ = self._template(name) File :\\Python27\\lib\\site-packages\\web\\template.py", line 1010, in _template self._cache[name] = self._load_template(name) File :\\Python27\\lib\\site-packages\\web\\template.py", line 1000, in _load_template raise AttributeError, "No template named + name AttributeError: No template named t1 |
错误是AttributeError: No template named t1, 貌似是说模板文件没找到.
网上搜索了一遍, 确认问题在于模板的路径不对. web.template.render('/tmplt/')这样写的话, 貌似Apache只会在C:\Program Files\Apache Software Foundation\Apache2.2这个所谓的网站服务器根目录下面去找tmplt文件夹,而不会自动使用相对路径去我们的代码文件夹里找.
所以我们必须给出这个tmplt的的全路径.用下面的代码, 可以不必在程序代码里写死路径:
|
…… root_dir=os.path.dirname(__file__) render = web.template.render(root_dir+'/tmplt/') ……
|
这样的话,在初始化render的时候就会去我们的代码文件夹下找模板文件夹目录了. 重启Apache后,网站正常运行了.
本文详细介绍了如何在Web.py框架中正确配置并使用模板系统。通过解决实际遇到的AttributeError错误,即找不到模板文件的问题,文章给出了明确的解决方案,并演示了如何通过获取当前文件的绝对路径来动态设置模板目录。
495

被折叠的 条评论
为什么被折叠?



