83 lines
2.4 KiB
Python
83 lines
2.4 KiB
Python
import re
|
|
import logging
|
|
from pathlib import Path
|
|
from django.http import HttpResponse
|
|
from django.conf import settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
TEMPLATE_DIR = Path(settings.BASE_DIR) / "TempLate"
|
|
|
|
|
|
def openr(filepath):
|
|
try:
|
|
with open(filepath, 'r', encoding='utf-8') as f:
|
|
return f.read()
|
|
except FileNotFoundError:
|
|
logger.warning(f"Template file not found: {filepath}")
|
|
return ''
|
|
except Exception as e:
|
|
logger.error(f"Error reading template file {filepath}: {e}")
|
|
return ''
|
|
|
|
|
|
def _resolve_url_for(endpoint):
|
|
endpoint_map = {
|
|
'UGM.UGM_Query_GetELTUserAvatar': '/Query/GetELTUserAvatar',
|
|
'MainLoginHTML': 'https://ugm.gvsds.com/login',
|
|
'GERP.GERPIndex': 'https://gerp.gvsds.com/',
|
|
'UGM.Index': 'https://ugm.gvsds.com/',
|
|
}
|
|
if endpoint in endpoint_map:
|
|
return endpoint_map[endpoint]
|
|
parts = endpoint.split('.')
|
|
if len(parts) >= 2:
|
|
return '/' + '/'.join(parts[1:])
|
|
return '/'
|
|
|
|
|
|
def ProcessTemplate(html_file, **kwargs):
|
|
html_path = TEMPLATE_DIR / html_file
|
|
html = openr(html_path)
|
|
|
|
base_path = TEMPLATE_DIR / "_Base"
|
|
footer_path = TEMPLATE_DIR / "_Footer"
|
|
|
|
use_base = kwargs.pop('UseBase', 'true')
|
|
no_footer = kwargs.pop('NoFooter', '')
|
|
sub_base = kwargs.pop('SubBase', None)
|
|
|
|
if sub_base:
|
|
sub_base_path = TEMPLATE_DIR / sub_base
|
|
_sub_base = openr(sub_base_path)
|
|
if _sub_base:
|
|
h = _sub_base.replace("{{ MAIN }}", html)
|
|
else:
|
|
h = html
|
|
elif use_base.lower() != 'false':
|
|
_base = openr(base_path)
|
|
_footer = openr(footer_path)
|
|
if _base:
|
|
h = _base.replace("{{ MAIN }}", html)
|
|
if no_footer:
|
|
h = h.replace("{{ Footer }}", "")
|
|
else:
|
|
h = h.replace("{{ Footer }}", _footer if _footer else "")
|
|
else:
|
|
h = html
|
|
else:
|
|
h = html
|
|
|
|
h = re.sub(r'\{\{\s*url_for\([\'"]([^\'"]+)[\'"]\)\s*\}\}', lambda m: _resolve_url_for(m.group(1)), h)
|
|
|
|
for key, value in kwargs.items():
|
|
h = h.replace("{{ %s }}" % key, str(value))
|
|
|
|
return h
|
|
|
|
|
|
def render_template(request, template_name, **kwargs):
|
|
kwargs.setdefault('UseBase', 'false')
|
|
content = ProcessTemplate(template_name, **kwargs)
|
|
return HttpResponse(content, content_type='text/html; charset=utf-8')
|