Python实现的简单模板引擎功能示例

所属分类: 脚本专栏 / python 阅读数: 1988
收藏 0 赞 0 分享

本文实例讲述了Python实现的简单模板引擎功能。分享给大家供大家参考,具体如下:

#coding:utf- 8
__author__="sdm"
__author_email='sdmzhu3@gmail.com'
__date__ ="$2009-8-25 21:04:13$"
'' '
pytpl 类似 php的模板类
'' '
import sys
import StringIO
import os.path
import os
#模 板的缓存
_tpl_cache={}
class Pytpl:
  def __init__(self,tpl_path='./' ):
    self.tpl_path=tpl_path
    self.data={}
    self.output = StringIO.StringIO()
    pass
  def set(self,name,value):
    '' '
    设 置模板变量
    '' '
    self.data[name]=value;
    pass
  def get(self,name):
    '' '
    得 到模板变量
    '' '
    t={}
    return t.get(name, '' )
    pass
  def tpl(self,tplname):
    '' '
    渲 染模板
    '' '
    f=self.tpl_path+tplname
    if not os.path.exists(f):
      raise Exception('tpl:[%s] is not exists' % f)
    mtime=os.stat(f).st_mtime
    if  not _tpl_cache.has_key(f) or _tpl_cache[f][ 'time' ]<mtime:
      src_code=self.__compile__(open(f).read())
      try :
        t=open(f+'.py' , 'w' )
        t.write(src_code)
        t.close()
      except:
        pass
      py_code=compile(src_code, f+'.py' , 'exec' )
      _tpl_cache[f]={'code' :py_code, 'time' :mtime}
    else :
      py_code= _tpl_cache[f]['code' ]
    exec(py_code, {'self' :self}, self.data)
    return self.output.getvalue()
  def execute(self,code,data,tplname):
    '' '
    执 行这个模板
    '' '
    py_file_name=tplname+'.py'
    f=open(py_file_name,'w' )
    f.write(code)
    f.close()
    execfile(py_file_name, {'self' :self}, data)
  def __compile__ (self,code):
    '' '
    编 译模板
    查找 <?标记
    '' '
    tlen=len(code);
    flag_start='<?'
    flag_end='?>'
    # 默认普通标记
    status=0
    i=0
    #分块 标记
    pos_end=0
    pos_start=0
    #缩 进
    global indent
    indent=0
    py_code=[]
    def place_t_code(c,t_indent):
      '' '
      基 本的代码处理
      '' '
      global indent
      if (c[ 0 ]== '=' ):
        return ( ' ' * 4 *indent) +  'echo ( /'%s/' % (' +c[ 1 :]+ '))'
      lines=c.split("/n" )
      t=[]
      for i in lines:
        indent2=indent
        tmp=i.strip("  /n/r" )
        c=tmp[len(tmp)-1 :len(tmp)]
        # 判定最后一个字符
        if (c== '{' ):
          indent+=1
          tmp=tmp[0 :len(tmp)- 1 ]+ ":"
        elif(c=='}' ):
          indent-=1
          tmp=tmp[0 :len(tmp)- 1 ]
        t.append((' ' * 4 *indent2) +tmp )
      return  "/n" .join(t)
    while  1 :
      if i>=tlen: break
      c=code[i];
      if status== 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
          if s:
            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
      if status== 1 :
        # 查找结束标记
        pos_end=code.find(flag_end,i)
        if (pos_end>- 1 ):
          # 需要跳过<? 这个标记
          t_code=place_t_code(code[pos_start+2 :pos_end],indent)
          # 跳过?>结束标记
          pos_end+=2
          py_code.append(t_code)
        else :
          # 没查找到直接结束
          pos_end=tlen
          # 需要跳过<? 这个标记
          t_code=place_t_code(code[pos_start+2 :pos_end],indent)
          py_code.append(t_code)
          break
        status=0
        i=pos_end
        pass
      i+=1
    py_code_str="#coding:utf-8/nimport sys;global echo;echo=self.output.write/n"
    py_code_str+="/n" .join(py_code)
    py_code_str=py_code_str.replace("/t" , "  " )
    return py_code_str
def test():
  tpl=Pytpl('./' );
  tpl.set('title' , '标题3' )
  print tpl.tpl('test.html' )
  pass
if __name__ == "__main__" :
  test()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

更多精彩内容其他人还在看

Python实现按学生年龄排序的实际问题详解

这篇文章主要给大家介绍了关于Python实现按学生年龄排序实际问题的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面跟着小编来一起学习学习吧。
收藏 0 赞 0 分享

Python开发的HTTP库requests详解

Requests是用Python语言编写,基于urllib,采用Apache2 Licensed开源协议的HTTP库。它比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试需求。Requests的哲学是以PEP 20 的习语为中心开发的,所以它比urllib更加P
收藏 0 赞 0 分享

Python网络爬虫与信息提取(实例讲解)

下面小编就为大家带来一篇Python网络爬虫与信息提取(实例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

在python3环境下的Django中使用MySQL数据库的实例

下面小编就为大家带来一篇在python3环境下的Django中使用MySQL数据库的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Python 3.x读写csv文件中数字的方法示例

在我们日常开发中经常需要对csv文件进行读写,下面这篇文章主要给大家介绍了关于Python 3.x读写csv文件中数字的相关资料,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面跟着小编来一起学习学习吧。
收藏 0 赞 0 分享

Python实现解析Bit Torrent种子文件内容的方法

这篇文章主要介绍了Python实现解析Bit Torrent种子文件内容的方法,结合实例形式分析了Python针对Torrent文件的读取与解析相关操作技巧与注意事项,需要的朋友可以参考下
收藏 0 赞 0 分享

Python实现文件内容批量追加的方法示例

这篇文章主要介绍了Python实现文件内容批量追加的方法,结合实例形式分析了Python文件的读写相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Python简单实现自动删除目录下空文件夹的方法

这篇文章主要介绍了Python简单实现自动删除目录下空文件夹的方法,涉及Python针对文件与目录的读取、判断、删除等相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

简单学习Python多进程Multiprocessing

这篇文章主要和大家一起简单的学习Python多进程Multiprocessing ,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Python导入模块时遇到的错误分析

这篇文章主要给大家详细解释了在Python处理导入模块的时候出现错误以及具体的情况分析,非常的详尽,有需要的小伙伴可以参考下
收藏 0 赞 0 分享
查看更多