This post demonstrates how to import code from external files and display images in the LeakIX Dark Theme.

Importing Code from Files

The theme supports importing code directly from files, which is useful for maintaining code examples separately from your content.

Go Example

Here’s a complete Go web server implementation imported from a file:

 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
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "time"
)

// Server represents our web server configuration
type Server struct {
    Host    string        `json:"host"`
    Port    int           `json:"port"`
    Timeout time.Duration `json:"timeout"`
}

// Response represents the API response structure
type Response struct {
    Status    string    `json:"status"`
    Message   string    `json:"message"`
    Timestamp time.Time `json:"timestamp"`
    Data      any       `json:"data,omitempty"`
}

// NewServer creates a new server instance with default values
func NewServer() *Server {
    return &Server{
        Host:    "localhost",
        Port:    8080,
        Timeout: 30 * time.Second,
    }
}

// Start initializes and starts the HTTP server
func (s *Server) Start() error {
    addr := fmt.Sprintf("%s:%d", s.Host, s.Port)

    mux := http.NewServeMux()
    mux.HandleFunc("/api/health", s.healthHandler)
    mux.HandleFunc("/api/data", s.dataHandler)

    server := &http.Server{
        Addr:         addr,
        Handler:      mux,
        ReadTimeout:  s.Timeout,
        WriteTimeout: s.Timeout,
    }

    log.Printf("Server starting on %s", addr)
    return server.ListenAndServe()
}

// healthHandler returns the server health status
func (s *Server) healthHandler(w http.ResponseWriter, r *http.Request) {
    response := Response{
        Status:    "success",
        Message:   "Server is healthy",
        Timestamp: time.Now(),
    }

    s.sendJSON(w, http.StatusOK, response)
}

// dataHandler returns sample data
func (s *Server) dataHandler(w http.ResponseWriter, r *http.Request) {
    data := map[string]interface{}{
        "items": []string{"item1", "item2", "item3"},
        "count": 3,
    }

    response := Response{
        Status:    "success",
        Message:   "Data retrieved successfully",
        Timestamp: time.Now(),
        Data:      data,
    }

    s.sendJSON(w, http.StatusOK, response)
}

// sendJSON sends a JSON response
func (s *Server) sendJSON(w http.ResponseWriter, status int, data any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)

    if err := json.NewEncoder(w).Encode(data); err != nil {
        log.Printf("Error encoding JSON: %v", err)
    }
}

func main() {
    server := NewServer()
    if err := server.Start(); err != nil {
        log.Fatalf("Server failed to start: %v", err)
    }
}

This server implementation shows:

  • Struct definitions with JSON tags
  • HTTP handler functions
  • Error handling patterns
  • JSON response formatting

Python Example

And here’s a Python task manager with async support:

  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
#!/usr/bin/env python3
"""
Example Python module demonstrating various features
for the LeakIX Dark Theme code highlighting showcase.
"""

import asyncio
import json
import logging
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import List, Optional, Dict, Any
from enum import Enum

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class TaskStatus(Enum):
    """Enumeration for task statuses"""
    PENDING = "pending"
    IN_PROGRESS = "in_progress"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELLED = "cancelled"


@dataclass
class Task:
    """Represents a task in our system"""
    id: str
    title: str
    description: str
    status: TaskStatus = TaskStatus.PENDING
    priority: int = 1
    created_at: datetime = field(default_factory=datetime.now)
    updated_at: datetime = field(default_factory=datetime.now)
    metadata: Dict[str, Any] = field(default_factory=dict)
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert task to dictionary representation"""
        return {
            'id': self.id,
            'title': self.title,
            'description': self.description,
            'status': self.status.value,
            'priority': self.priority,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'metadata': self.metadata
        }
    
    def update_status(self, new_status: TaskStatus) -> None:
        """Update task status and timestamp"""
        self.status = new_status
        self.updated_at = datetime.now()
        logger.info(f"Task {self.id} status updated to {new_status.value}")


class TaskManager:
    """Manages a collection of tasks"""
    
    def __init__(self):
        self.tasks: Dict[str, Task] = {}
        self._task_counter = 0
    
    def create_task(self, title: str, description: str, **kwargs) -> Task:
        """Create a new task"""
        self._task_counter += 1
        task_id = f"TASK-{self._task_counter:04d}"
        
        task = Task(
            id=task_id,
            title=title,
            description=description,
            **kwargs
        )
        
        self.tasks[task_id] = task
        logger.info(f"Created task: {task_id}")
        return task
    
    def get_task(self, task_id: str) -> Optional[Task]:
        """Retrieve a task by ID"""
        return self.tasks.get(task_id)
    
    def list_tasks(self, status: Optional[TaskStatus] = None) -> List[Task]:
        """List all tasks, optionally filtered by status"""
        tasks = list(self.tasks.values())
        
        if status:
            tasks = [t for t in tasks if t.status == status]
        
        return sorted(tasks, key=lambda t: (t.priority, t.created_at))
    
    async def process_task(self, task_id: str) -> bool:
        """Process a task asynchronously"""
        task = self.get_task(task_id)
        if not task:
            logger.error(f"Task {task_id} not found")
            return False
        
        try:
            task.update_status(TaskStatus.IN_PROGRESS)
            
            # Simulate processing time
            await asyncio.sleep(2)
            
            # Simulate random success/failure
            import random
            if random.random() > 0.8:
                raise Exception("Random failure for demonstration")
            
            task.update_status(TaskStatus.COMPLETED)
            return True
            
        except Exception as e:
            logger.error(f"Task {task_id} failed: {e}")
            task.update_status(TaskStatus.FAILED)
            return False
    
    def export_tasks(self, filename: str) -> None:
        """Export all tasks to a JSON file"""
        tasks_data = [task.to_dict() for task in self.tasks.values()]
        
        with open(filename, 'w') as f:
            json.dump(tasks_data, f, indent=2, default=str)
        
        logger.info(f"Exported {len(tasks_data)} tasks to {filename}")
    
    def get_statistics(self) -> Dict[str, Any]:
        """Get statistics about tasks"""
        stats = {
            'total': len(self.tasks),
            'by_status': {},
            'by_priority': {},
            'avg_age_hours': 0
        }
        
        for task in self.tasks.values():
            # Count by status
            status_key = task.status.value
            stats['by_status'][status_key] = stats['by_status'].get(status_key, 0) + 1
            
            # Count by priority
            priority_key = f"priority_{task.priority}"
            stats['by_priority'][priority_key] = stats['by_priority'].get(priority_key, 0) + 1
        
        # Calculate average age
        if self.tasks:
            now = datetime.now()
            total_age = sum((now - t.created_at).total_seconds() for t in self.tasks.values())
            stats['avg_age_hours'] = round(total_age / len(self.tasks) / 3600, 2)
        
        return stats


async def main():
    """Main entry point for the application"""
    manager = TaskManager()
    
    # Create sample tasks
    tasks = [
        manager.create_task("Setup environment", "Install required dependencies", priority=1),
        manager.create_task("Write documentation", "Create comprehensive docs", priority=2),
        manager.create_task("Run tests", "Execute test suite", priority=1),
        manager.create_task("Deploy application", "Deploy to production", priority=3),
    ]
    
    # Process tasks concurrently
    results = await asyncio.gather(
        *[manager.process_task(task.id) for task in tasks],
        return_exceptions=True
    )
    
    # Display statistics
    stats = manager.get_statistics()
    print("\n=== Task Statistics ===")
    print(f"Total tasks: {stats['total']}")
    print(f"By status: {stats['by_status']}")
    print(f"By priority: {stats['by_priority']}")
    print(f"Average age: {stats['avg_age_hours']} hours")
    
    # Export results
    manager.export_tasks("tasks_export.json")


if __name__ == "__main__":
    asyncio.run(main())

The Python example demonstrates:

  • Dataclasses and type hints
  • Async/await patterns
  • Enum usage
  • JSON serialization

Working with Images

The theme provides excellent support for images with automatic dark mode optimization.

Dark Theme Preview The LeakIX Dark Theme in action

Responsive Images

The theme automatically handles responsive images:

Responsive Design

Code Comparison

Sometimes you want to show before and after code examples:

Before Optimization

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Inefficient code
function processData(items) {
  let results = [];
  for (let i = 0; i < items.length; i++) {
    if (items[i].active === true) {
      results.push(items[i]);
    }
  }
  return results;
}

After Optimization

1
2
// Optimized code
const processData = items => items.filter(item => item.active);

Inline Code Examples

You can also include smaller code snippets inline. For example, to install the theme: hugo new site mysite && cd mysite && git clone https://github.com/LeakIX/leakix-dark-theme themes/leakix-dark.

Architecture Diagrams

graph TD
    A[User Request] --> B[Hugo Router]
    B --> C{Page Type}
    C -->|Single| D[Single Template]
    C -->|List| E[List Template]
    C -->|Home| F[Index Template]
    D --> G[Render with Theme]
    E --> G
    F --> G
    G --> H[HTML Output]

Configuration Examples

Theme Configuration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
[params]
  # Enable code file imports
  enableCodeImports = true

  # Image optimization
  imageOptimization = true
  lazyLoadImages = true

  # Syntax highlighting theme
  syntaxTheme = "monokai"

Summary

The LeakIX Dark Theme provides comprehensive support for:

  • Code imports from external files
  • Image handling with dark mode optimization
  • Responsive design for all screen sizes
  • Syntax highlighting with multiple themes
  • Mermaid diagrams for architecture visualization

All these features work together to create a powerful platform for technical content.