Python实现的简单模板引擎功能示例
本文实例讲述了Python实现的简单模板引擎功能。分享给大家供大家参考,具体如下:
#coding:utf-8
__author__="sdm"
__author_email='sdmzhu3@gmail.com'
__date__="$2009-8-2521:04:13$"
'''
pytpl类似php的模板类
'''
importsys
importStringIO
importos.path
importos
#模板的缓存
_tpl_cache={}
classPytpl:
def__init__(self,tpl_path='./'):
self.tpl_path=tpl_path
self.data={}
self.output=StringIO.StringIO()
pass
defset(self,name,value):
'''
设置模板变量
'''
self.data[name]=value;
pass
defget(self,name):
'''
得到模板变量
'''
t={}
returnt.get(name,'')
pass
deftpl(self,tplname):
'''
渲染模板
'''
f=self.tpl_path+tplname
ifnotos.path.exists(f):
raiseException('tpl:[%s]isnotexists'%f)
mtime=os.stat(f).st_mtime
ifnot_tpl_cache.has_key(f)or_tpl_cache[f]['time']=tlen:break
c=code[i];
ifstatus==0:
#编译加速
pos_start=code.find(flag_start,pos_end);
if(pos_start>-1):
s=code[pos_end:pos_start]
t_code='echo('+repr(s)+')'
t_code=''*indent*4+t_code
ifs:
py_code.append(t_code)
i=pos_start
last_pos=i
#进入代码状态
status=1
continue
else:
#没有没有找到
pos_start=tlen
t_code='echo('+repr(code[pos_end:pos_start])+')'
t_code=''*indent*4+t_code
py_code.append(t_code)
break
ifstatus==1:
#查找结束标记
pos_end=code.find(flag_end,i)
if(pos_end>-1):
#需要跳过结束标记
pos_end+=2
py_code.append(t_code)
else:
#没查找到直接结束
pos_end=tlen
#需要跳过
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。