apppublic/appPublic/myTE.py

67 lines
1.8 KiB
Python
Raw Normal View History

2019-07-29 09:59:10 +08:00
import os
import sys
2019-09-16 15:11:14 +08:00
try:
import ujson as json
except:
import json
2019-07-29 09:59:10 +08:00
from jinja2 import Environment,FileSystemLoader
import codecs
from appPublic.argsConvert import ArgsConvert
from appPublic.dictObject import DictObject
def isNone(obj):
return obj is None
class MyTemplateEngine:
def __init__(self,pathList,file_coding='utf-8',out_coding='utf-8'):
self.file_coding = file_coding
self.out_coding = out_coding
loader = FileSystemLoader(pathList, encoding=self.file_coding)
2021-01-25 12:07:56 +08:00
self.env = Environment(loader=loader, enable_async=True)
2019-07-29 09:59:10 +08:00
denv={
'json':json,
'hasattr':hasattr,
'int':int,
'float':float,
'str':str,
'type':type,
'isNone':isNone,
'len':len,
'render':self.render,
'renders':self.renders,
'ArgsConvert':ArgsConvert,
'renderJsonFile':self.renderJsonFile,
'ospath':lambda x:os.path.sep.join(x.split(os.altsep)),
'basename':lambda x:os.path.basename(x),
'basenameWithoutExt':lambda x:os.path.splitext(os.path.basename(x))[0],
'extname':lambda x:os.path.splitext(x)[-1],
}
self.env.globals.update(denv)
2019-08-12 11:55:18 +08:00
def set(self,k,v):
self.env.globals.update({k:v})
2019-07-29 09:59:10 +08:00
def _render(self,template,data):
2019-09-16 15:11:14 +08:00
# print('**********template=',template,'**data=',data,'type_data=',type(data),'************')
2021-01-25 12:07:56 +08:00
uRet = await template.render_async(**data)
2019-08-12 11:55:18 +08:00
return uRet
2019-07-29 09:59:10 +08:00
def renders(self,tmplstring,data):
def getGlobal():
return data
self.set('global',getGlobal)
template = self.env.from_string(tmplstring)
return self._render(template,data)
def render(self,tmplfile,data):
def getGlobal():
return data
self.set('global',getGlobal)
template = self.env.get_template(tmplfile)
return self._render(template,data)
def renderJsonFile(self,tmplfile,jsonfile):
2019-08-12 11:55:18 +08:00
with codecs.open(jsonfile,"r",self.file_coding) as f:
data = json.load(f)
return self.render(tmplfile,data)