Spaces:
Running
Running
| """ | |
| Unified escaping helpers for HTML rendering. | |
| Keep all HTML/attribute/script escaping logic in one place to avoid divergence. | |
| """ | |
| import json | |
| from typing import Any | |
| def escape_text_node(text: str) -> str: | |
| """Escape text for HTML text node insertion.""" | |
| if text is None: | |
| return "" | |
| return ( | |
| text.replace("&", "&") | |
| .replace("<", "<") | |
| .replace(">", ">") | |
| ) | |
| def escape_attr(text: str) -> str: | |
| """Escape text for safe placement in HTML attribute values.""" | |
| if text is None: | |
| return "" | |
| return ( | |
| text.replace("&", "&") | |
| .replace('"', """) | |
| .replace("'", "'") | |
| .replace("<", "<") | |
| .replace(">", ">") | |
| .replace("\n", " ") | |
| .replace("\r", " ") | |
| .replace("\t", "	") | |
| ) | |
| def escape_json_for_script(value: Any) -> str: | |
| """Serialize JSON for safe embedding inside <script> tags.""" | |
| text = json.dumps(value, ensure_ascii=False) | |
| # Prevent closing tags or HTML entities from breaking script context. | |
| return ( | |
| text.replace("<", "\\u003c") | |
| .replace(">", "\\u003e") | |
| .replace("&", "\\u0026") | |
| ) | |