-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathai-llms.txt
More file actions
1298 lines (1108 loc) · 37.7 KB
/
ai-llms.txt
File metadata and controls
1298 lines (1108 loc) · 37.7 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Template Engine - AI Development Assistant
## Project Overview
This is a powerful Go template engine with comprehensive multi-theme support, hot reloading, embedded filesystem support, and split template architecture. The engine provides complete backward compatibility while offering advanced features for modern web applications.
**Latest Version Features:**
- ✅ Multi-theme support with runtime switching
- ✅ Split template architecture for better code organization
- ✅ Complete backward compatibility (zero-modification upgrades)
- ✅ Performance optimized with efficient resource management
- ✅ Comprehensive test coverage including property-based testing
- ✅ Production-ready with extensive error handling
## Core Features
### Multi-Theme Support
- **Runtime theme switching** without server restart
- **Automatic theme discovery** and validation
- **Theme configuration** via theme.json files
- **Complete backward compatibility** with single-theme projects
- **Mixed mode support** (traditional + theme directories coexist)
- **Theme inheritance** and customization capabilities
### Split Template Architecture
- **Modular templates** split into multiple files (header.tmpl, content.tmpl, script.tmpl)
- **Separation of concerns** with different `define` blocks
- **Theme-specific styling**, content, and JavaScript logic
- **Automatic loading** and compilation of split templates
- **Backward compatibility** with monolithic template files
- **Reduced file bloat** and improved maintainability
### Template Loading System
- **Dual filesystem support** (file system and embedded filesystem)
- **Hot reloading** during development with file watching
- **Automatic template discovery** and validation
- **Custom template function** support with FuncMap
- **Efficient caching** and resource management
- **Error recovery** and graceful degradation
## Architecture
### System Architecture Overview
```
┌─────────────────────────────────────────────────────────────┐
│ User Layer │
├─────────────────────────┬───────────────────────────────────┤
│ Existing Code │ New Multi-Theme Code │
│ (Zero Changes) │ (Optional Features) │
└─────────────────────────┼───────────────────────────────────┘
│
┌─────────────────────────┼───────────────────────────────────┐
│ Engine Layer │
│ ┌─────────────────────┐│┌─────────────────────────────────┐ │
│ │ Legacy Mode │││ Multi-Theme Mode │ │
│ │ (Traditional) │││ (Enhanced) │ │
│ └─────────────────────┘│└─────────────────────────────────┘ │
└─────────────────────────┼───────────────────────────────────┘
│
┌─────────────────────────┼───────────────────────────────────┐
│ Theme Management Layer │
│ ┌─────────────────────┐│┌─────────────────────────────────┐ │
│ │ Auto Detection │││ Theme Manager │ │
│ │ (Mode Selection) │││ (Discovery & Switching) │ │
│ └─────────────────────┘│└─────────────────────────────────┘ │
└─────────────────────────┼───────────────────────────────────┘
│
┌─────────────────────────┼───────────────────────────────────┐
│ Storage Layer │
│ ┌─────────────────────┐│┌─────────────────────────────────┐ │
│ │ File System │││ Embedded FS │ │
│ │ (Development) │││ (Production) │ │
│ └─────────────────────┘│└─────────────────────────────────┘ │
└─────────────────────────┴───────────────────────────────────┘
```
### Key Components
1. **Engine** (`engine.go`)
- **Main template engine** with multi-theme support
- **Backward compatible API** preserving all existing methods
- **Automatic mode detection** (legacy vs multi-theme)
- **Methods**: Init(), SwitchTheme(), RenderPage(), RenderSingle(), RenderError()
- **Theme management** and template rendering coordination
2. **ThemeManager** (`theme.go`)
- **Theme discovery** and loading with validation
- **Theme metadata management** via theme.json files
- **Template compilation** per theme with caching
- **Runtime theme switching** with state management
- **Error handling** and recovery mechanisms
3. **Options** (`options.go`)
- **Configuration system** for engine setup with backward compatibility
- **New options**: EnableMultiTheme(), DefaultTheme(), Theme()
- **Existing options**: GlobalConstant(), GlobalVariable() (unchanged)
- **Progressive enhancement** approach for new features
4. **Template Functions** (`template_func.go`)
- **Template loading logic** for both file system and embedded FS
- **Split template support** in page directories
- **Automatic discovery** of layouts, pages, singles, errors, and partials
- **Backward compatibility** with traditional template structures
### Template Structure
#### Traditional Structure (Backward Compatible)
```
templates/
├── layouts/
│ └── layout.tmpl # Main layout template
├── pages/
│ └── [page-name]/
│ └── page.tmpl # Page template with define blocks
├── singles/
│ └── [page].tmpl # Standalone pages
├── errors/
│ └── [code].tmpl # Error pages
└── partials/
└── [partial].tmpl # Reusable components
```
#### Multi-Theme Structure (Enhanced)
```
templates/
├── [theme-name]/
│ ├── theme.json # Theme configuration
│ ├── layouts/
│ │ ├── layout.tmpl # Main layout template
│ │ ├── single.tmpl # Layout for singles
│ │ └── error.tmpl # Layout for errors
│ ├── pages/
│ │ └── [page-name]/
│ │ ├── header.tmpl # {{ define "header" }}
│ │ ├── content.tmpl # {{ define "content" }}
│ │ └── script.tmpl # {{ define "script" }}
│ ├── singles/
│ │ └── [page]/
│ │ ├── header.tmpl # Split single templates
│ │ ├── content.tmpl
│ │ ├── style.tmpl
│ │ └── script.tmpl
│ ├── errors/
│ │ └── [code]/
│ │ ├── header.tmpl # Split error templates
│ │ ├── content.tmpl
│ │ ├── style.tmpl
│ │ └── script.tmpl
│ └── partials/
│ └── [partial].tmpl # Reusable components
└── [another-theme]/ # Additional themes
└── ... # Same structure
```
#### Mixed Mode Support
```
templates/
├── layouts/ # Traditional structure (default theme)
├── pages/
├── singles/
├── errors/
├── partials/
├── dark/ # Additional theme
│ ├── layouts/
│ ├── pages/
│ └── ...
└── colorful/ # Another theme
├── layouts/
├── pages/
└── ...
```
## API Reference
### Engine Creation
#### Basic Single-Theme Engine (Backward Compatible)
```go
// Traditional approach - no changes required
engine, err := template.NewEngine("./templates", template.DefaultLoadTemplate, funcMap)
if err != nil {
log.Fatal(err)
}
engine.Init()
```
#### Multi-Theme Engine (Enhanced)
```go
// Multi-theme with automatic detection
engine, err := template.NewEngine("./templates", template.DefaultLoadTemplate, funcMap,
template.EnableMultiTheme(true), // Enable multi-theme mode
template.DefaultTheme("default"), // Set default theme
)
if err != nil {
log.Fatal(err)
}
engine.Init()
// Switch to specific theme
err = engine.SwitchTheme("dark")
if err != nil {
log.Printf("Theme switch failed: %v", err)
}
```
#### Embedded Filesystem Engine
```go
//go:embed templates/*
var tmplFS embed.FS
// Embedded filesystem with multi-theme support
engine, err := template.NewEngineWithEmbedFS(&tmplFS, "templates",
template.DefaultLoadTemplateWithEmbedFS, funcMap,
template.EnableMultiTheme(true),
template.DefaultTheme("default"),
)
if err != nil {
log.Fatal(err)
}
engine.Init()
```
### Engine Methods
#### Core Rendering Methods (Unchanged)
```go
// Initialize the engine (required)
engine.Init()
// Rendering methods - identical signatures
err := engine.RenderPage(w, "page-name", data)
err := engine.RenderSingle(w, "single-name", data)
err := engine.RenderError(w, "error-code", data)
// Development features
err := engine.Watching() // Enable hot reloading
engine.Close() // Cleanup resources
```
#### Theme Management Methods (New)
```go
// Get available themes
themes := engine.GetAvailableThemes()
// Returns: []string{"default", "dark", "colorful"}
// Get current active theme
current := engine.GetCurrentTheme()
// Returns: "default"
// Switch theme at runtime
err := engine.SwitchTheme("dark")
if err != nil {
log.Printf("Theme switch failed: %v", err)
}
// Check if theme exists
exists := engine.ThemeExists("dark")
// Returns: true/false
```
### Configuration Options
#### Backward Compatible Options
```go
// All existing options work unchanged
template.GlobalConstant(map[string]interface{}{
"siteName": "My Website",
"version": "1.0.0",
})
template.GlobalVariable(map[string]interface{}{
"year": time.Now().Year(),
})
```
#### New Multi-Theme Options
```go
// Enable multi-theme mode (optional)
template.EnableMultiTheme(true)
// Set default theme (optional)
template.DefaultTheme("theme-name")
// Set initial theme (deprecated - use SwitchTheme instead)
template.Theme("theme-name")
```
## Split Template Implementation
### Template File Organization
Split templates allow better code organization by separating concerns:
#### Page Template Structure
```
pages/posts/list/
├── header.tmpl # Page head, CSS, meta tags
├── content.tmpl # Main page content
└── script.tmpl # JavaScript code
```
#### Singles Template Structure
```
singles/login/
├── header.tmpl # Page head and styles
├── content.tmpl # Login form content
├── style.tmpl # CSS styles
└── script.tmpl # JavaScript logic
```
#### Errors Template Structure
```
errors/404/
├── header.tmpl # Error page head
├── content.tmpl # Error message content
├── style.tmpl # Error page styles
└── script.tmpl # Error handling scripts
```
### Define Blocks
Each split template file must use the appropriate define block:
#### header.tmpl
```html
{{ define "header" }}
<title>{{ .title }} - {{ .constant.siteName }}</title>
<meta name="description" content="{{ .description }}">
<style>
/* Theme-specific CSS styles */
body { font-family: Arial, sans-serif; }
.container { max-width: 1200px; margin: 0 auto; }
</style>
{{ end }}
```
#### content.tmpl
```html
{{ define "content" }}
<h1>{{ .title }}</h1>
<div class="main-content">
{{ range .items }}
<article>
<h2>{{ .title }}</h2>
<p>{{ .summary }}</p>
</article>
{{ end }}
</div>
{{ end }}
```
#### script.tmpl
```html
{{ define "script" }}
<script>
document.addEventListener('DOMContentLoaded', function() {
// Theme-specific JavaScript logic
console.log('Current theme: {{ .currentTheme }}');
// Interactive features
initializeThemeFeatures();
});
function initializeThemeFeatures() {
// Theme-specific functionality
}
</script>
{{ end }}
```
### Layout Integration
Layout templates must include all define blocks:
#### Main Layout (layout.tmpl)
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{ template "header" . }}
</head>
<body>
<header>
<nav><!-- Navigation --></nav>
</header>
<main>
{{ template "content" . }}
</main>
<footer>
<p>© {{ .variable.year }} {{ .constant.siteName }}</p>
</footer>
{{ template "script" . }}
</body>
</html>
```
#### Specialized Layouts
```html
<!-- singles layout (single.tmpl) -->
<!DOCTYPE html>
<html>
<head>
{{ template "header" . }}
{{ template "style" . }}
</head>
<body>
{{ template "content" . }}
{{ template "script" . }}
</body>
</html>
<!-- error layout (error.tmpl) -->
<!DOCTYPE html>
<html>
<head>
{{ template "header" . }}
{{ template "style" . }}
</head>
<body class="error-page">
{{ template "content" . }}
{{ template "script" . }}
</body>
</html>
```
### Backward Compatibility
The system supports both split and monolithic templates:
#### Traditional Monolithic Template
```html
<!-- pages/posts/list.tmpl -->
{{ define "header" }}<title>Posts</title>{{ end }}
{{ define "content" }}
<h1>Posts</h1>
<div>Content here...</div>
{{ end }}
```
#### Split Template Alternative
```
pages/posts/list/
├── header.tmpl # {{ define "header" }}<title>Posts</title>{{ end }}
├── content.tmpl # {{ define "content" }}<h1>Posts</h1>...{{ end }}
└── script.tmpl # {{ define "script" }}...{{ end }}
```
Both approaches work identically - the system automatically detects and loads the appropriate structure.
## Theme Configuration
### theme.json Structure
Each theme can include a configuration file describing its metadata:
```json
{
"name": "theme-name",
"displayName": "Theme Display Name",
"description": "Detailed theme description",
"version": "1.0.0",
"author": "Author Name",
"tags": ["tag1", "tag2", "responsive"],
"custom": {
"primaryColor": "#2c3e50",
"accentColor": "#3498db",
"backgroundColor": "#ffffff",
"features": ["dark-mode", "animations"],
"targetAudience": "business"
}
}
```
### Theme Configuration Examples
#### Default Theme
```json
{
"name": "default",
"displayName": "默认主题",
"description": "简洁的默认主题,适合日常使用",
"version": "1.0.0",
"author": "开发团队",
"tags": ["default", "clean", "simple"],
"custom": {
"primaryColor": "#2c3e50",
"accentColor": "#3498db",
"backgroundColor": "#ffffff"
}
}
```
#### Dark Theme
```json
{
"name": "dark",
"displayName": "深色主题",
"description": "深色背景,护眼设计",
"version": "1.0.0",
"author": "开发团队",
"tags": ["dark", "night", "professional"],
"custom": {
"primaryColor": "#1a1a1a",
"accentColor": "#bb86fc",
"backgroundColor": "#121212"
}
}
```
### Accessing Theme Configuration
```go
// In template functions or handlers
themeConfig := engine.GetThemeMetadata("dark")
if themeConfig != nil {
primaryColor := themeConfig.Custom["primaryColor"]
features := themeConfig.Custom["features"]
}
// In templates
{{ .themeConfig.displayName }}
{{ .themeConfig.custom.primaryColor }}
```
## Development Guidelines
### Creating New Themes
#### Step 1: Create Theme Directory Structure
```bash
mkdir -p templates/my-theme/{layouts,pages,singles,errors,partials}
```
#### Step 2: Copy Base Theme Templates
```bash
# Copy from existing theme as starting point
cp -r templates/default/* templates/my-theme/
```
#### Step 3: Customize Theme Templates
```bash
# Edit theme-specific styles and content
vim templates/my-theme/layouts/layout.tmpl
vim templates/my-theme/pages/home/header.tmpl
```
#### Step 4: Create Theme Configuration
```bash
# Create theme.json
cat > templates/my-theme/theme.json << EOF
{
"name": "my-theme",
"displayName": "My Custom Theme",
"description": "A custom theme for my application",
"version": "1.0.0",
"author": "Your Name",
"tags": ["custom", "unique"],
"custom": {
"primaryColor": "#your-color"
}
}
EOF
```
#### Step 5: Test Theme Functionality
```go
// Test theme switching
err := engine.SwitchTheme("my-theme")
if err != nil {
log.Printf("Theme switch failed: %v", err)
}
// Verify theme is available
themes := engine.GetAvailableThemes()
fmt.Printf("Available themes: %v\n", themes)
```
### Split Template Best Practices
#### 1. Separation of Concerns
- **header.tmpl**: Only page metadata, title, and CSS
- **content.tmpl**: Only HTML structure and content
- **script.tmpl**: Only JavaScript logic and interactions
- **style.tmpl**: Only CSS styles (for singles/errors)
#### 2. Consistency Across Themes
```bash
# Maintain same file structure across all themes
templates/
├── default/
│ └── pages/posts/list/
│ ├── header.tmpl
│ ├── content.tmpl
│ └── script.tmpl
├── dark/
│ └── pages/posts/list/
│ ├── header.tmpl # Same structure
│ ├── content.tmpl # Same structure
│ └── script.tmpl # Same structure
└── colorful/
└── pages/posts/list/
├── header.tmpl # Same structure
├── content.tmpl # Same structure
└── script.tmpl # Same structure
```
#### 3. Template Independence
```html
<!-- Avoid dependencies between template files -->
<!-- BAD: content.tmpl depending on script.tmpl -->
{{ define "content" }}
<div id="dynamic-content">
<!-- This assumes script.tmpl will handle #dynamic-content -->
</div>
{{ end }}
<!-- GOOD: self-contained content -->
{{ define "content" }}
<div class="posts-list">
{{ range .posts }}
<article>{{ .title }}</article>
{{ end }}
</div>
{{ end }}
```
#### 4. Theme Differentiation
```html
<!-- Each theme can have unique behavior -->
<!-- default/pages/home/script.tmpl -->
{{ define "script" }}
<script>
// Simple, clean interactions
document.addEventListener('click', handleClick);
</script>
{{ end }}
<!-- colorful/pages/home/script.tmpl -->
{{ define "script" }}
<script>
// Rich, animated interactions
document.addEventListener('click', handleClickWithAnimation);
initializeParticleEffects();
</script>
{{ end }}
```
### Testing Themes
#### Unit Testing
```go
func TestThemeRendering(t *testing.T) {
engine, err := template.NewEngine("./templates", template.DefaultLoadTemplate, nil,
template.EnableMultiTheme(true),
)
require.NoError(t, err)
engine.Init()
// Test each theme
themes := engine.GetAvailableThemes()
for _, theme := range themes {
t.Run(theme, func(t *testing.T) {
err := engine.SwitchTheme(theme)
require.NoError(t, err)
var buf bytes.Buffer
err = engine.RenderPage(&buf, "home", template.H{
"title": "Test Page",
})
require.NoError(t, err)
assert.Contains(t, buf.String(), "Test Page")
})
}
}
```
#### Integration Testing
```go
func TestThemeSwitchingInWebApp(t *testing.T) {
// Test theme switching via HTTP endpoints
server := httptest.NewServer(createHandler())
defer server.Close()
// Test theme switch
resp, err := http.Post(server.URL+"/switch-theme",
"application/x-www-form-urlencoded",
strings.NewReader("theme=dark"))
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
```
#### Performance Testing
```go
func BenchmarkThemeSwitching(b *testing.B) {
engine := setupEngine()
themes := []string{"default", "dark", "colorful"}
b.ResetTimer()
for i := 0; i < b.N; i++ {
theme := themes[i%len(themes)]
engine.SwitchTheme(theme)
}
}
```
## Common Patterns
### Custom Template Functions
```go
funcMap := template.FuncMap{
// Date formatting
"formatDate": func(t time.Time) string {
return t.Format("2006-01-02 15:04:05")
},
// List creation
"list": func(items ...interface{}) []interface{} {
return items
},
// Math operations
"mod": func(a, b int) int {
return a % b
},
// Theme-aware functions
"themeAsset": func(path string) string {
currentTheme := engine.GetCurrentTheme()
return fmt.Sprintf("/assets/%s/%s", currentTheme, path)
},
// Conditional rendering based on theme
"ifTheme": func(themeName string, content interface{}) interface{} {
if engine.GetCurrentTheme() == themeName {
return content
}
return ""
},
}
```
### Theme Switching Handler
```go
func switchThemeHandler(w http.ResponseWriter, r *http.Request) {
themeName := r.FormValue("theme")
// Validate theme exists
if !engine.ThemeExists(themeName) {
http.Error(w, "Theme not found", http.StatusBadRequest)
return
}
// Switch theme
if err := engine.SwitchTheme(themeName); err != nil {
log.Printf("Theme switch failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Store theme preference (optional)
http.SetCookie(w, &http.Cookie{
Name: "theme",
Value: themeName,
Path: "/",
})
// Redirect back
http.Redirect(w, r, r.Header.Get("Referer"), http.StatusSeeOther)
}
```
### Theme Management API
```go
func themesAPIHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
// Get available themes
themes := engine.GetAvailableThemes()
current := engine.GetCurrentTheme()
response := map[string]interface{}{
"themes": themes,
"current": current,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
case "POST":
// Switch theme
var req struct {
Theme string `json:"theme"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
if err := engine.SwitchTheme(req.Theme); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
}
}
```
### Data Structure for Templates
```go
// Standard template data structure
data := template.H{
"title": "Page Title",
"currentTheme": engine.GetCurrentTheme(),
"content": "Page content",
"posts": []Post{...},
// Theme-specific data
"themeConfig": engine.GetThemeMetadata(engine.GetCurrentTheme()),
// Global constants (available in all templates)
"constant": map[string]interface{}{
"siteName": "My Website",
"version": "2.0.0",
},
// Global variables (can change)
"variable": map[string]interface{}{
"year": time.Now().Year(),
"user": getCurrentUser(r),
},
}
```
### Middleware for Theme Management
```go
func themeMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check for theme preference in cookie
if cookie, err := r.Cookie("theme"); err == nil {
if engine.ThemeExists(cookie.Value) {
engine.SwitchTheme(cookie.Value)
}
}
// Check for theme parameter in URL
if theme := r.URL.Query().Get("theme"); theme != "" {
if engine.ThemeExists(theme) {
engine.SwitchTheme(theme)
// Set cookie for future requests
http.SetCookie(w, &http.Cookie{
Name: "theme",
Value: theme,
Path: "/",
})
}
}
next.ServeHTTP(w, r)
})
}
```
### Error Handling Patterns
```go
func renderWithFallback(w http.ResponseWriter, templateName string, data interface{}) {
err := engine.RenderPage(w, templateName, data)
if err != nil {
log.Printf("Template rendering failed: %v", err)
// Try fallback theme
currentTheme := engine.GetCurrentTheme()
if currentTheme != "default" {
log.Printf("Trying fallback theme: default")
if switchErr := engine.SwitchTheme("default"); switchErr == nil {
if fallbackErr := engine.RenderPage(w, templateName, data); fallbackErr == nil {
return
}
// Switch back to original theme
engine.SwitchTheme(currentTheme)
}
}
// Final fallback - render error page
engine.RenderError(w, "500", template.H{
"error": "Template rendering failed",
})
}
}
```
## Error Handling
### Common Errors
- Theme not found: Verify theme directory exists and has required structure
- Template parsing errors: Check template syntax and define blocks
- Missing template files: Ensure all required templates exist in theme
### Debugging
- Enable verbose logging
- Check theme discovery results
- Validate template compilation
- Monitor theme switching operations
## Performance Considerations
- Templates are compiled once per theme
- Only active theme templates are loaded into memory
- Hot reloading is for development only
- Use embedded filesystem for production deployments
## Backward Compatibility
### Complete Compatibility Guarantee
The multi-theme feature is designed with **progressive enhancement** principles, ensuring existing projects work without any modifications:
#### API Compatibility
- All existing method signatures remain unchanged
- `NewEngine()`, `RenderPage()`, `RenderSingle()`, `RenderError()` work exactly as before
- Configuration options are fully backward compatible
- Error handling behavior is preserved
#### Directory Structure Compatibility
- Traditional single-theme structure continues to work
- Automatic mode detection (legacy vs multi-theme)
- Mixed mode support (traditional + theme directories)
#### Performance Compatibility
- Legacy mode performance identical to original version
- Multi-theme features only loaded when needed
- Memory usage patterns preserved
#### Migration Path
```go
// Zero-modification upgrade
engine, err := template.NewEngine("./templates", template.DefaultLoadTemplate, funcMap)
// Identical behavior, no changes required
// Progressive multi-theme enablement
engine, err := template.NewEngine("./templates", template.DefaultLoadTemplate, funcMap,
template.EnableMultiTheme(true), // Optional new feature
)
```
### From Single Theme to Multi-Theme
1. Move existing templates to `templates/default/` directory
2. Add `template.EnableMultiTheme(true)` option
3. Update initialization code to use `SwitchTheme()` instead of `Theme()` option
4. Test backward compatibility
### To Split Templates
1. Identify separable components (CSS, content, JS)
2. Create separate .tmpl files with appropriate define blocks
3. Update layout template to include all blocks
4. Test rendering functionality
## Production Deployment
### Docker Integration
```dockerfile
# Multi-stage build for embedded themes
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o app .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/app .
COPY --from=builder /app/templates ./templates
CMD ["./app"]
```
### Environment Configuration
```go
func setupProductionEngine() (*template.Engine, error) {
var engine *template.Engine
var err error
if os.Getenv("USE_EMBEDDED_TEMPLATES") == "true" {
// Production: use embedded templates
engine, err = template.NewEngineWithEmbedFS(&tmplFS, "templates",
template.DefaultLoadTemplateWithEmbedFS, funcMap,
template.EnableMultiTheme(true),
template.DefaultTheme(os.Getenv("DEFAULT_THEME")),
)
} else {
// Development: use file system
engine, err = template.NewEngine("./templates", template.DefaultLoadTemplate, funcMap,
template.EnableMultiTheme(true),
template.DefaultTheme("default"),
)
}
if err != nil {
return nil, err
}
engine.Init()