2019-07-10 17:34:45 +08:00
|
|
|
import os
|
|
|
|
import codecs
|
|
|
|
|
|
|
|
from appPublic.Singleton import SingletonDecorator
|
|
|
|
from appPublic.jsonConfig import getConfig
|
|
|
|
|
|
|
|
from jinja2 import Template,Environment, BaseLoader
|
|
|
|
from .serverenv import ServerEnv
|
|
|
|
from .url2file import Url2File, TmplUrl2File
|
|
|
|
|
|
|
|
class TmplLoader(BaseLoader, TmplUrl2File):
|
|
|
|
def __init__(self, paths, indexes, subffixes=['.tmpl'], inherit=False):
|
|
|
|
BaseLoader.__init__(self)
|
|
|
|
TmplUrl2File.__init__(self,paths,indexes=indexes,subffixes=subffixes, inherit=inherit)
|
|
|
|
|
|
|
|
def get_source(self,env: Environment,template: str):
|
|
|
|
config = getConfig()
|
|
|
|
coding = config.website.coding
|
2020-12-20 11:43:00 +08:00
|
|
|
|
2019-07-10 17:34:45 +08:00
|
|
|
fp = self.url2file(template)
|
|
|
|
if not os.path.isfile(fp):
|
2024-02-18 16:50:29 +08:00
|
|
|
print(f'{template=} can not transfer to filename')
|
2019-07-10 17:34:45 +08:00
|
|
|
raise TemplateNotFound(template)
|
|
|
|
mtime = os.path.getmtime(fp)
|
|
|
|
with codecs.open(fp,'r',coding) as f:
|
|
|
|
source = f.read()
|
|
|
|
return source,fp,lambda:mtime == os.path.getmtime(fp)
|
|
|
|
|
|
|
|
def join_path(self,name, parent):
|
|
|
|
return self.relatedurl(parent,name)
|
|
|
|
|
|
|
|
def list_templates(self):
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
|
|
class TemplateEngine(Environment):
|
|
|
|
def __init__(self,loader=None):
|
2021-01-25 12:03:19 +08:00
|
|
|
Environment.__init__(self,loader=loader, enable_async=True)
|
2019-07-10 17:34:45 +08:00
|
|
|
self.urlpaths = {}
|
|
|
|
self.loader = loader
|
|
|
|
|
|
|
|
def join_path(self,template: str, parent: str):
|
|
|
|
return self.loader.join_path(template, parent)
|
|
|
|
|
2021-01-25 12:03:19 +08:00
|
|
|
async def render(self,___name: str, **globals):
|
2019-11-29 18:01:58 +08:00
|
|
|
t = self.get_template(___name,globals=globals)
|
2021-01-25 12:03:19 +08:00
|
|
|
return await t.render_async(globals)
|
2019-07-10 17:34:45 +08:00
|
|
|
|
|
|
|
def setupTemplateEngine():
|
|
|
|
config = getConfig()
|
|
|
|
subffixes = [ i[0] for i in config.website.processors if i[1] == 'tmpl' ]
|
2019-12-05 06:04:38 +08:00
|
|
|
loader = TmplLoader(config.website.paths,
|
|
|
|
config.website.indexes,
|
|
|
|
subffixes,
|
|
|
|
inherit=True)
|
2019-07-10 17:34:45 +08:00
|
|
|
engine = TemplateEngine(loader)
|
|
|
|
g = ServerEnv()
|
|
|
|
g.tmpl_engine = engine
|
|
|
|
|