82 lines
2.3 KiB
Python
82 lines
2.3 KiB
Python
#!/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]}...')"
|