初始提交,未完全测试
This commit is contained in:
81
template/stat/ast/Text.py
Normal file
81
template/stat/ast/Text.py
Normal file
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3.9
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
JFinal Text - Text Statement
|
||||
"""
|
||||
|
||||
from .Stat import Stat
|
||||
from ..Scope import Scope
|
||||
from ...Env import Env
|
||||
|
||||
class Text(Stat):
|
||||
"""Text statement for template content"""
|
||||
|
||||
def __init__(self, content: str):
|
||||
"""
|
||||
Initialize text statement
|
||||
|
||||
Args:
|
||||
content: Text content
|
||||
"""
|
||||
self._content = content
|
||||
|
||||
def exec(self, env: Env, scope: Scope, writer) -> None:
|
||||
"""
|
||||
Execute text statement
|
||||
|
||||
Args:
|
||||
env: Template environment
|
||||
scope: Execution scope
|
||||
writer: Output writer
|
||||
"""
|
||||
if hasattr(writer, 'write'):
|
||||
# Parse and evaluate template expressions
|
||||
parsed_content = self._parse_expressions(env, scope)
|
||||
writer.write(parsed_content)
|
||||
|
||||
def _parse_expressions(self, env: Env, scope: Scope) -> str:
|
||||
"""
|
||||
Parse and evaluate template expressions in content
|
||||
|
||||
Args:
|
||||
env: Template environment
|
||||
scope: Execution scope
|
||||
|
||||
Returns:
|
||||
Parsed and evaluated content
|
||||
"""
|
||||
import re
|
||||
|
||||
def replace_expression(match):
|
||||
"""Replace expression with evaluated value"""
|
||||
expr_str = match.group(1).strip()
|
||||
|
||||
# Try to evaluate expression
|
||||
try:
|
||||
# First try variable access
|
||||
if expr_str.isidentifier():
|
||||
value = scope.get(expr_str)
|
||||
return str(value) if value is not None else ''
|
||||
|
||||
# Try arithmetic expression
|
||||
try:
|
||||
# Simple arithmetic evaluation
|
||||
# This is a simplified implementation
|
||||
result = eval(expr_str, {})
|
||||
return str(result)
|
||||
except:
|
||||
pass
|
||||
|
||||
# Fallback to original expression
|
||||
return match.group(0)
|
||||
|
||||
except Exception as e:
|
||||
return f"{match.group(0)} [Error: {e}]"
|
||||
|
||||
# Replace all #(...) expressions
|
||||
pattern = r'#\((.*?)\)'
|
||||
return re.sub(pattern, replace_expression, self._content)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Text('{self._content[:50]}...')"
|
||||
Reference in New Issue
Block a user