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


Posted in Python onSeptember 02, 2017

本文实例讲述了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执行等待程序直到第二天零点的方法
Apr 23 Python
Python中的ConfigParser模块使用详解
May 04 Python
Python中List.index()方法的使用教程
May 20 Python
一篇文章读懂Python赋值与拷贝
Apr 19 Python
python实现简单http服务器功能
Sep 17 Python
浅谈python下tiff图像的读取和保存方法
Dec 04 Python
Django应用程序入口WSGIHandler源码解析
Aug 05 Python
python代码实现逻辑回归logistic原理
Aug 07 Python
基于Python解密仿射密码
Oct 21 Python
Python+OpenCV实现图像的全景拼接
Mar 05 Python
Python面向对象多态实现原理及代码实例
Sep 16 Python
python绘制高斯曲线
Feb 19 Python
Python实现Logger打印功能的方法详解
Sep 01 #Python
Python数据分析之如何利用pandas查询数据示例代码
Sep 01 #Python
Python使用回溯法子集树模板解决迷宫问题示例
Sep 01 #Python
Python基于回溯法子集树模板实现8皇后问题
Sep 01 #Python
Python3.x对JSON的一些操作示例
Sep 01 #Python
Python+Socket实现基于TCP协议的客户与服务端中文自动回复聊天功能示例
Aug 31 #Python
Python+Socket实现基于UDP协议的局域网广播功能示例
Aug 31 #Python
You might like
Yii框架参数配置文件params用法实例分析
2019/09/11 PHP
jQuery 表单验证扩展代码(一)
2010/10/11 Javascript
EasyUi tabs的高度与宽度根据IE窗口的变化自适应代码
2010/10/26 Javascript
jQuery编辑器KindEditor4.1.4代码高亮显示设置教程
2013/03/01 Javascript
jquery append()方法与html()方法的区别及使用介绍
2014/08/01 Javascript
JavaScript正则表达式之multiline属性的应用
2015/06/16 Javascript
四种参数传递的形式——URL,超链接,js,form表单
2015/07/24 Javascript
AngularJS整合Springmvc、Spring、Mybatis搭建开发环境
2016/02/25 Javascript
如何在Linux上安装Node.js
2016/04/01 Javascript
浅谈js中的延迟执行和定时执行
2016/05/31 Javascript
原生js实现键盘控制div移动且解决停顿问题
2016/12/05 Javascript
jquery横向纵向鼠标滚轮全屏切换
2017/02/27 Javascript
详解ESLint在Vue中的使用小结
2018/10/15 Javascript
详解微信小程序与内嵌网页交互实现支付功能
2018/10/22 Javascript
微信小程序 setData 对 data数据影响问题
2019/04/18 Javascript
Vue通过阿里云oss的url连接直接下载文件并修改文件名的方法
2020/12/25 Vue.js
Python 变量类型及命名规则介绍
2013/06/08 Python
Python函数式编程指南(一):函数式编程概述
2015/06/24 Python
python中安装Scrapy模块依赖包汇总
2017/07/02 Python
利用django-suit模板添加自定义的菜单、页面及设置访问权限
2018/07/13 Python
Python单向链表和双向链表原理与用法实例详解
2018/08/31 Python
对Python中plt的画图函数详解
2018/11/07 Python
树莓派与PC端在局域网内运用python实现即时通讯
2019/06/22 Python
pandas中的数据去重处理的实现方法
2020/02/10 Python
Python3.7 读取音频根据文件名生成脚本的代码
2020/04/07 Python
python中四舍五入的正确打开方式
2021/01/18 Python
UGG澳洲官网:UGG Australia
2018/04/26 全球购物
Java基础知识面试要点
2016/07/29 面试题
全陪导游欢迎词
2014/01/17 职场文书
企业员工培训感言
2014/02/26 职场文书
企业演讲稿范文大全
2014/05/20 职场文书
法院授权委托书范文
2014/08/02 职场文书
党支部创先争优承诺书
2014/08/30 职场文书
故意杀人罪辩护词
2015/05/21 职场文书
Nginx 反向代理解决跨域问题多种情况分析
2022/01/18 Servers
vue使用element-ui按需引入
2022/05/20 Vue.js