-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusage_guide.py
More file actions
184 lines (146 loc) · 5.87 KB
/
usage_guide.py
File metadata and controls
184 lines (146 loc) · 5.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CustomTemplateEngine - Complete Usage Guide for Unicode and Template Types
This guide shows how to use the CustomTemplateEngine for both text and HTML templates
with full Unicode support.
"""
from template_engine import TemplateEngine
def usage_examples():
"""Complete usage examples for text and HTML templates with Unicode."""
print("📚 CustomTemplateEngine - Usage Guide")
print("=" * 60)
# Sample Unicode data
data = {
'title': 'Международный сайт 🌍', # Russian + emoji
'user': 'José María', # Spanish accents
'greeting': 'こんにちは', # Japanese
'description': 'Welcome & bienvenue!', # Special chars
'items': [
{'name': 'Café', 'price': '3.50 EUR'},
{'name': '抹茶', 'price': '400 JPY'},
{'name': 'Coffee', 'price': '2.99 USD'}
]
}
print("\n1. 📝 TEXT TEMPLATES (No HTML escaping)")
print("-" * 40)
# Create text engine
text_engine = TemplateEngine(auto_escape=False, strict_mode=False)
text_template = '''Title: $title
User: $user
Greeting: $greeting
Description: $description
Menu Items:
{% for item in items %}
- $item.name: $item.price
{% endfor %}'''
# Using render() with auto_escape=False
result1 = text_engine.render(text_template, data)
print("Text template result:")
print(result1)
print("\n2. 🌐 HTML TEMPLATES (With XSS protection)")
print("-" * 40)
# Create HTML engine
html_engine = TemplateEngine(auto_escape=True, strict_mode=False)
html_template = '''<div class="content">
<h1>$title</h1>
<p>Welcome <strong>$user</strong>!</p>
<p>$greeting</p>
<p class="description">$description</p>
<ul class="menu">
{% for item in items %}
<li>$item.name - $item.price</li>
{% endfor %}
</ul>
</div>'''
# Using render() with auto_escape=True
result2 = html_engine.render(html_template, data)
print("HTML template result:")
print(result2)
print("\n3. 💾 SAVING TO FILES")
print("-" * 40)
# Save HTML result to file
html_result = html_engine.render(html_template, data)
with open('output.html', 'w', encoding='utf-8') as f:
f.write(html_result)
# Save text result to file
text_result = text_engine.render(text_template, data)
with open('output.txt', 'w', encoding='utf-8') as f:
f.write(text_result)
print("✅ Files saved successfully")
print("\n4. 🔤 ENCODING SUPPORT")
print("-" * 40)
# Different encodings
for encoding in ['utf-8', 'utf-16']:
engine = TemplateEngine(auto_escape=False)
with open(f'unicode_{encoding.replace("-", "_")}.txt', 'w', encoding=encoding) as f:
result = engine.render(text_template, data)
f.write(result)
print(f"✅ Saved with {encoding} encoding")
print("\n5. 🔒 SECURITY FEATURES")
print("-" * 40)
dangerous_data = {
'user_input': '<script>alert("hack")</script>',
'safe_content': 'Normal content',
'html_tags': '<b>Bold text</b>'
}
security_template = '''User Input: $user_input
Safe Content: $safe_content
HTML Tags: $html_tags'''
# Safe (escaped) version
safe_engine = TemplateEngine(auto_escape=True)
safe_result = safe_engine.render(security_template, dangerous_data)
print("🔒 SAFE (HTML escaped):")
print(safe_result)
# Unsafe (raw) version
unsafe_engine = TemplateEngine(auto_escape=False)
unsafe_result = unsafe_engine.render(security_template, dangerous_data)
print("⚠️ UNSAFE (no escaping):")
print(unsafe_result)
print("\n6. 📊 BEST PRACTICES")
print("-" * 40)
print("""
✅ DO:
- Use render() with auto_escape=True for HTML templates
- Use render() with auto_escape=False for plain text templates
- Enable auto_escape for HTML content
- Use UTF-8 encoding by default
- Handle missing variables gracefully with strict_mode=False
❌ DON'T:
- Disable auto_escape for user-generated HTML content
- Mix text and HTML rendering without considering security
- Ignore Unicode encoding when saving files
- Use strict_mode=True without proper error handling
🌍 UNICODE SUPPORT:
- Full emoji support: 🎉🚀💫⭐🌟
- International languages: العربية 中文 日本語 Русский
- Special characters: àáâãäåæçèéêë
- Mathematical symbols: ∑∏∆∇∂∫∞≠≤≥
- Currency symbols: €£¥¢$
""")
def template_type_comparison():
"""Show the differences between text and HTML template handling."""
print("\n🔍 TEMPLATE TYPE COMPARISON")
print("=" * 60)
data = {'content': '<b>Bold</b> & "quoted" text 🎉'}
template = 'Content: $content'
# Text engine (no escaping)
text_engine = TemplateEngine(auto_escape=False)
text_result = text_engine.render(template, data)
# HTML engine (with escaping)
html_engine = TemplateEngine(auto_escape=True)
html_result = html_engine.render(template, data)
print(f"Original data: {data['content']}")
print(f"Text result: {text_result.strip()}")
print(f"HTML result: {html_result.strip()}")
print("\n📝 Key Differences:")
print("• Text templates (auto_escape=False) preserve all characters exactly")
print("• HTML templates (auto_escape=True) escape dangerous characters for security")
print("• Both support full Unicode including emojis and international text")
print("• Use the same render() method with different auto_escape settings")
if __name__ == "__main__":
usage_examples()
template_type_comparison()
print("\n🎉 Usage Guide Complete!")
print("Files generated: output.html, output.txt")
print("Unicode files: unicode_utf_8.txt, unicode_utf_16.txt")