初始提交: LiteAdmin 社区平台
This commit is contained in:
+433
@@ -0,0 +1,433 @@
|
||||
import datetime
|
||||
import html as html_module
|
||||
import os
|
||||
import re
|
||||
import urllib.parse
|
||||
|
||||
|
||||
_VAR_RE = re.compile(r'\{\{(.*?)\}\}')
|
||||
_BLOCK_RE = re.compile(r'\{%(.*?)%\}')
|
||||
_COMMENT_RE = re.compile(r'\{#.*?#\}')
|
||||
|
||||
|
||||
def _resolve_val(context, name):
|
||||
parts = name.split('.')
|
||||
val = context.get(parts[0], '') if isinstance(context, dict) else getattr(context, parts[0], '')
|
||||
for part in parts[1:]:
|
||||
if val is None or val == '':
|
||||
return ''
|
||||
if isinstance(val, dict):
|
||||
val = val.get(part, '')
|
||||
else:
|
||||
val = getattr(val, part, '')
|
||||
if val is None:
|
||||
return ''
|
||||
return val
|
||||
|
||||
|
||||
def _apply_filter_chain(value, filter_chain, filters):
|
||||
for f in filter_chain:
|
||||
f = f.strip()
|
||||
if '(' in f:
|
||||
fname, args_str = f.split('(', 1)
|
||||
args_str = args_str.rstrip(')')
|
||||
args = [a.strip() for a in args_str.split(',') if a.strip()]
|
||||
resolved_args = []
|
||||
for arg in args:
|
||||
if arg.startswith("'") or arg.startswith('"'):
|
||||
resolved_args.append(arg.strip("'\""))
|
||||
else:
|
||||
resolved_args.append(arg)
|
||||
if fname.strip() in filters:
|
||||
value = filters[fname.strip()](value, *resolved_args)
|
||||
else:
|
||||
if f in filters:
|
||||
value = filters[f](value)
|
||||
return value
|
||||
|
||||
|
||||
def _tokenize(source):
|
||||
tokens = []
|
||||
pos = 0
|
||||
while pos < len(source):
|
||||
comment_m = _COMMENT_RE.match(source, pos)
|
||||
if comment_m:
|
||||
pos = comment_m.end()
|
||||
continue
|
||||
var_m = _VAR_RE.match(source, pos)
|
||||
if var_m:
|
||||
tokens.append(('var', var_m.group(1)))
|
||||
pos = var_m.end()
|
||||
continue
|
||||
block_m = _BLOCK_RE.match(source, pos)
|
||||
if block_m:
|
||||
tokens.append(('block', block_m.group(1)))
|
||||
pos = block_m.end()
|
||||
continue
|
||||
next_pos = len(source)
|
||||
for pattern in [_VAR_RE, _BLOCK_RE, _COMMENT_RE]:
|
||||
m = pattern.search(source, pos)
|
||||
if m and m.start() < next_pos:
|
||||
next_pos = m.start()
|
||||
text = source[pos:next_pos]
|
||||
if text:
|
||||
tokens.append(('text', text))
|
||||
pos = next_pos
|
||||
return tokens
|
||||
|
||||
|
||||
def _compile_tokens_to_func(tokens, engine, block_override=None):
|
||||
code_lines = ['def _render(context, _filters, _escape, _globals, _include, _resolve_val, _apply_filter_chain):']
|
||||
code_lines.append(' _ctx = dict(context)')
|
||||
code_lines.append(' _buf = []')
|
||||
indent = 1
|
||||
block_stack = []
|
||||
i = 0
|
||||
|
||||
while i < len(tokens):
|
||||
ttype, tval = tokens[i]
|
||||
if ttype == 'text':
|
||||
escaped = tval.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n')
|
||||
code_lines.append(' ' * indent + "_buf.append('{}')".format(escaped))
|
||||
i += 1
|
||||
elif ttype == 'var':
|
||||
var_raw = tval.strip()
|
||||
filter_parts = []
|
||||
if '|' in var_raw:
|
||||
parts = var_raw.split('|')
|
||||
expr_part = parts[0].strip()
|
||||
filter_parts = [p.strip() for p in parts[1:]]
|
||||
else:
|
||||
expr_part = var_raw
|
||||
base = _translate_to_ctx(expr_part)
|
||||
for f in filter_parts:
|
||||
base = "_apply_filter_chain({}, ['{}'], _filters)".format(base, f)
|
||||
code_lines.append(' ' * indent + "_buf.append(str(_escape({})))".format(base))
|
||||
i += 1
|
||||
elif ttype == 'block':
|
||||
raw = tval.strip()
|
||||
cmd = raw.split(None, 1)
|
||||
command = cmd[0] if cmd else ''
|
||||
args = cmd[1].strip() if len(cmd) > 1 else ''
|
||||
|
||||
if command == 'if':
|
||||
cond = _translate_to_ctx(args)
|
||||
code_lines.append(' ' * indent + 'if {}:'.format(cond))
|
||||
block_stack.append(('if', indent))
|
||||
indent += 1
|
||||
elif command == 'elif':
|
||||
indent -= 1
|
||||
cond = _translate_to_ctx(args)
|
||||
code_lines.append(' ' * indent + 'elif {}:'.format(cond))
|
||||
block_stack[-1] = ('if', indent)
|
||||
indent += 1
|
||||
elif command == 'else':
|
||||
indent -= 1
|
||||
code_lines.append(' ' * indent + 'else:')
|
||||
block_stack[-1] = (block_stack[-1][0], indent)
|
||||
indent += 1
|
||||
elif command == 'endif':
|
||||
if block_stack and block_stack[-1][0] == 'if':
|
||||
indent = block_stack[-1][1]
|
||||
block_stack.pop()
|
||||
elif command == 'for':
|
||||
parts = args.split(None, 2)
|
||||
if len(parts) >= 3 and parts[1] == 'in':
|
||||
vname = parts[0]
|
||||
iterable = _translate_to_ctx(parts[2])
|
||||
code_lines.append(' ' * indent + 'for {} in {}:'.format(vname, iterable))
|
||||
code_lines.append(' ' * (indent + 1) + "_ctx['{}'] = {}".format(vname, vname))
|
||||
block_stack.append(('for', indent))
|
||||
indent += 1
|
||||
else:
|
||||
code_lines.append(' ' * indent + 'pass')
|
||||
elif command == 'endfor':
|
||||
if block_stack and block_stack[-1][0] == 'for':
|
||||
indent = block_stack[-1][1]
|
||||
block_stack.pop()
|
||||
elif command == 'set':
|
||||
eq_pos = args.find('=')
|
||||
if eq_pos > 0:
|
||||
vname = args[:eq_pos].strip()
|
||||
value_expr = _translate_to_ctx(args[eq_pos + 1:].strip())
|
||||
code_lines.append(' ' * indent + "{} = {}".format(vname, value_expr))
|
||||
code_lines.append(' ' * indent + "_ctx['{}'] = {}".format(vname, vname))
|
||||
elif command == 'block':
|
||||
block_name = args.strip()
|
||||
code_lines.append(' ' * indent +
|
||||
"if '{}' in _ctx.get('_blocks', {{}}):".format(block_name))
|
||||
code_lines.append(' ' * (indent + 1) +
|
||||
"_buf.append(_ctx['_blocks']['{}'](_ctx, _filters, _escape, _globals, _include, _resolve_val, _apply_filter_chain))".format(block_name))
|
||||
code_lines.append(' ' * indent + 'else:')
|
||||
code_lines.append(' ' * (indent + 2) + 'pass')
|
||||
block_stack.append(('block', indent, block_name))
|
||||
indent += 2
|
||||
elif command == 'endblock':
|
||||
if block_stack and block_stack[-1][0] == 'block':
|
||||
indent = block_stack[-1][1]
|
||||
block_stack.pop()
|
||||
elif command == 'include':
|
||||
inc_name = args.strip().strip("'\"").strip('"\'')
|
||||
code_lines.append(' ' * indent + "_buf.append(_include('{}', _ctx, _filters, _escape, _globals))".format(inc_name))
|
||||
elif command == 'extends':
|
||||
pass
|
||||
elif command == 'macro':
|
||||
paren_pos = args.find('(')
|
||||
if paren_pos > 0:
|
||||
macro_name = args[:paren_pos].strip()
|
||||
macro_params = args[paren_pos:]
|
||||
code_lines.append(' ' * indent + 'def _macro_{}{}:'.format(macro_name, macro_params))
|
||||
code_lines.append(' ' * (indent + 1) + '_mbuf = []')
|
||||
block_stack.append(('macro', indent, macro_name))
|
||||
indent += 1
|
||||
elif command == 'endmacro':
|
||||
if block_stack and block_stack[-1][0] == 'macro':
|
||||
indent = block_stack[-1][1]
|
||||
macro_name = block_stack[-1][2]
|
||||
code_lines.append(' ' * (indent + 1) + "return ''.join(_mbuf)")
|
||||
code_lines.append(' ' * indent + "_buf.append(_macro_{}())".format(macro_name))
|
||||
block_stack.pop()
|
||||
i += 1
|
||||
|
||||
code_lines.append(' return "".join(_buf)')
|
||||
return '\n'.join(code_lines)
|
||||
|
||||
|
||||
def _translate_to_ctx(expr):
|
||||
expr = expr.strip()
|
||||
if expr in ('True', 'False', 'None'):
|
||||
return expr
|
||||
|
||||
result = []
|
||||
i = 0
|
||||
while i < len(expr):
|
||||
if expr[i] in ("'", '"'):
|
||||
quote = expr[i]
|
||||
j = i + 1
|
||||
while j < len(expr):
|
||||
if expr[j] == '\\':
|
||||
j += 2
|
||||
continue
|
||||
if expr[j] == quote:
|
||||
j += 1
|
||||
break
|
||||
j += 1
|
||||
result.append(expr[i:j])
|
||||
i = j
|
||||
elif expr[i].isalpha() or expr[i] == '_':
|
||||
j = i
|
||||
while j < len(expr) and (expr[j].isalnum() or expr[j] in '_.'):
|
||||
j += 1
|
||||
var_name = expr[i:j]
|
||||
if var_name not in ('True', 'False', 'None', 'and', 'or', 'not', 'in', 'is'):
|
||||
result.append("_resolve_val(_ctx, '{}')".format(var_name))
|
||||
else:
|
||||
result.append(var_name)
|
||||
i = j
|
||||
else:
|
||||
result.append(expr[i])
|
||||
i += 1
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def _extract_blocks(tokens):
|
||||
blocks = {}
|
||||
i = 0
|
||||
while i < len(tokens):
|
||||
ttype, tval = tokens[i]
|
||||
if ttype == 'block' and tval.strip().startswith('block '):
|
||||
block_name = tval.strip()[6:].strip()
|
||||
depth = 1
|
||||
j = i + 1
|
||||
while j < len(tokens) and depth > 0:
|
||||
tj_type, tj_val = tokens[j]
|
||||
if tj_type == 'block':
|
||||
cmd = tj_val.strip().split(None, 1)
|
||||
c = cmd[0] if cmd else ''
|
||||
if c == 'block':
|
||||
depth += 1
|
||||
elif c == 'endblock':
|
||||
depth -= 1
|
||||
j += 1
|
||||
block_tokens = tokens[i + 1:j - 1]
|
||||
blocks[block_name] = block_tokens
|
||||
i = j
|
||||
else:
|
||||
i += 1
|
||||
return blocks
|
||||
|
||||
|
||||
def _find_extends(tokens):
|
||||
if tokens and tokens[0][0] == 'block':
|
||||
val = tokens[0][1].strip()
|
||||
if val.startswith('extends '):
|
||||
parent_name = val[8:].strip().strip("'\"").strip('"\'')
|
||||
return parent_name
|
||||
return None
|
||||
|
||||
|
||||
class Template:
|
||||
def __init__(self, source, name='<string>', engine=None):
|
||||
self.source = source
|
||||
self.name = name
|
||||
self.engine = engine
|
||||
self.compiled_func = None
|
||||
self._compile()
|
||||
|
||||
def _compile(self):
|
||||
tokens = _tokenize(self.source)
|
||||
parent_name = _find_extends(tokens)
|
||||
if parent_name and self.engine:
|
||||
child_blocks = _extract_blocks(tokens)
|
||||
try:
|
||||
parent_source = self.engine._load_template(parent_name)
|
||||
parent_tokens = _tokenize(parent_source)
|
||||
code = _compile_tokens_to_func(parent_tokens, self.engine)
|
||||
namespace = {}
|
||||
exec(code, namespace)
|
||||
render_func = namespace['_render']
|
||||
|
||||
def wrapped_render(context, filters, escape_func, globals_dict, include_func,
|
||||
_resolve_val, _apply_filter_chain):
|
||||
ctx = dict(context)
|
||||
ctx['_blocks'] = {}
|
||||
for bname, btokens in child_blocks.items():
|
||||
bcode = _compile_tokens_to_func(btokens, self.engine)
|
||||
bns = {}
|
||||
exec(bcode, bns)
|
||||
ctx['_blocks'][bname] = bns['_render']
|
||||
return render_func(ctx, filters, escape_func, globals_dict, include_func,
|
||||
_resolve_val, _apply_filter_chain)
|
||||
|
||||
self.compiled_func = wrapped_render
|
||||
return
|
||||
except Exception as e:
|
||||
print('[模板继承错误] {} 在 "{}" 继承 "{}"'.format(e, self.name, parent_name))
|
||||
self.compiled_func = None
|
||||
return
|
||||
|
||||
code = _compile_tokens_to_func(tokens, self.engine)
|
||||
namespace = {}
|
||||
try:
|
||||
exec(code, namespace)
|
||||
self.compiled_func = namespace['_render']
|
||||
except Exception as e:
|
||||
self.compiled_func = None
|
||||
print('[模板编译错误] {} 在模板 "{}" 中'.format(e, self.name))
|
||||
|
||||
def render(self, context, filters, escape_func, globals_dict, include_func):
|
||||
if self.compiled_func is None:
|
||||
return '[模板编译失败: {}]'.format(self.name)
|
||||
try:
|
||||
return self.compiled_func(
|
||||
context, filters, escape_func, globals_dict, include_func,
|
||||
_resolve_val, _apply_filter_chain
|
||||
)
|
||||
except TypeError as e:
|
||||
return '[模板渲染错误: {} - 参数数量不匹配]'.format(e)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
return '[模板渲染错误: {}]'.format(e)
|
||||
|
||||
|
||||
class TemplateEngine:
|
||||
def __init__(self):
|
||||
self.template_dirs = []
|
||||
self.cache = {}
|
||||
self._filters = {}
|
||||
self._globals = {}
|
||||
self._setup_filters()
|
||||
self._setup_globals()
|
||||
|
||||
def _setup_filters(self):
|
||||
self._filters.update({
|
||||
'upper': lambda v: str(v).upper() if v is not None else '',
|
||||
'lower': lambda v: str(v).lower() if v is not None else '',
|
||||
'escape': lambda v: html_module.escape(str(v)) if v is not None else '',
|
||||
'safe': lambda v: v,
|
||||
'capitalize': lambda v: str(v).capitalize() if v else '',
|
||||
'title': lambda v: str(v).title() if v else '',
|
||||
'trim': lambda v: str(v).strip() if v else '',
|
||||
'length': lambda v: len(v) if hasattr(v, '__len__') else len(str(v or '')),
|
||||
'reverse': lambda v: v[::-1] if hasattr(v, '__getitem__') else str(v or '')[::-1],
|
||||
'first': lambda v: v[0] if v else '',
|
||||
'last': lambda v: v[-1] if v else '',
|
||||
'join': lambda v, sep=', ': sep.join(str(x) for x in (v or [])),
|
||||
'default': lambda v, d='': v if v else d,
|
||||
'int': lambda v: int(v) if v else 0,
|
||||
'float': lambda v: float(v) if v else 0.0,
|
||||
'str': lambda v: str(v),
|
||||
'urlencode': lambda v: urllib.parse.quote(str(v)),
|
||||
'truncate': lambda v, l=100: (str(v)[:l] + '...') if len(str(v)) > l else str(v),
|
||||
'date': lambda v, fmt='%Y-%m-%d': v.strftime(fmt) if hasattr(v, 'strftime') else str(v),
|
||||
})
|
||||
|
||||
def _setup_globals(self):
|
||||
self._globals['now'] = datetime.datetime.now
|
||||
self._globals['range'] = range
|
||||
self._globals['dict'] = dict
|
||||
self._globals['list'] = list
|
||||
self._globals['len'] = len
|
||||
self._globals['str'] = str
|
||||
self._globals['int'] = int
|
||||
|
||||
def add_template_dir(self, directory):
|
||||
abs_dir = os.path.abspath(directory)
|
||||
if abs_dir not in self.template_dirs:
|
||||
self.template_dirs.append(abs_dir)
|
||||
|
||||
def add_filter(self, name, func):
|
||||
self._filters[name] = func
|
||||
|
||||
def add_global(self, name, value):
|
||||
self._globals[name] = value
|
||||
|
||||
def _escape(self, value):
|
||||
if hasattr(value, '__html__'):
|
||||
return str(value)
|
||||
return html_module.escape(str(value))
|
||||
|
||||
def _load_template(self, template_name):
|
||||
for directory in self.template_dirs:
|
||||
filepath = os.path.join(directory, template_name)
|
||||
if os.path.isfile(filepath):
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
return f.read()
|
||||
raise FileNotFoundError('模板未找到: {}'.format(template_name))
|
||||
|
||||
def _include(self, template_name, context, filters, escape_func, globals_dict):
|
||||
t = self._get_template(template_name)
|
||||
return t.render(context, filters, escape_func, globals_dict, self._include)
|
||||
|
||||
def _get_template(self, template_name):
|
||||
if template_name in self.cache:
|
||||
return self.cache[template_name]
|
||||
source = self._load_template(template_name)
|
||||
t = Template(source, name=template_name, engine=self)
|
||||
self.cache[template_name] = t
|
||||
return t
|
||||
|
||||
def render(self, template_name, context=None):
|
||||
if context is None:
|
||||
context = {}
|
||||
context = dict(context)
|
||||
template = self._get_template(template_name)
|
||||
return template.render(context, self._filters, self._escape, self._globals, self._include)
|
||||
|
||||
def render_string(self, source, context=None, template_name='<string>'):
|
||||
if context is None:
|
||||
context = {}
|
||||
context = dict(context)
|
||||
key = 'str:{}'.format(hash(source))
|
||||
if key not in self.cache:
|
||||
t = Template(source, name=template_name, engine=self)
|
||||
self.cache[key] = t
|
||||
return self.cache[key].render(context, self._filters, self._escape, self._globals, self._include)
|
||||
|
||||
|
||||
class _SafeString(str):
|
||||
pass
|
||||
|
||||
|
||||
def mark_safe(value):
|
||||
return _SafeString(value)
|
||||
Reference in New Issue
Block a user