Skip to content

Code Samples

This page demonstrates all advanced code block features available in Material for MkDocs, showcasing syntax highlighting, line numbers, annotations, and interactive elements.

Basic Syntax Highlighting

Python

def fibonacci(n: int) -> int:
    """Calculate the nth Fibonacci number."""
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

# Example usage
numbers = [fibonacci(i) for i in range(10)]
print(f"First 10 Fibonacci numbers: {numbers}")

JavaScript

class Calculator {
    constructor() {
        this.history = [];
    }

    add(a, b) {
        const result = a + b;
        this.history.push(`${a} + ${b} = ${result}`);
        return result;
    }

    getHistory() {
        return this.history.join('\n');
    }
}

const calc = new Calculator();
console.log(calc.add(5, 3)); // 8

TypeScript

interface User {
    id: number;
    name: string;
    email: string;
    isActive: boolean;
}

class UserService {
    private users: User[] = [];

    async createUser(userData: Omit<User, 'id'>): Promise<User> {
        const newUser: User = {
            id: this.generateId(),
            ...userData
        };

        this.users.push(newUser);
        return newUser;
    }

    private generateId(): number {
        return Math.max(...this.users.map(u => u.id), 0) + 1;
    }
}

Line Numbers and Highlighting

With Line Numbers

import asyncio
import aiohttp
from typing import List, Dict, Optional

async def fetch_data(session: aiohttp.ClientSession, url: str) -> Optional[Dict]:
    """Fetch data from a URL asynchronously."""
    try:
        async with session.get(url) as response:
            if response.status == 200:
                return await response.json()
            else:
                print(f"Error {response.status} for {url}")
                return None
    except Exception as e:
        print(f"Exception fetching {url}: {e}")
        return None

async def fetch_multiple(urls: List[str]) -> List[Dict]:
    """Fetch data from multiple URLs concurrently."""
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_data(session, url) for url in urls]
        results = await asyncio.gather(*tasks, return_exceptions=True)
        return [r for r in results if isinstance(r, dict)]

Highlighting Specific Lines

def process_user_data(users: List[Dict]) -> Dict[str, int]:
    """Process user data and return statistics."""
    # Data validation - highlighted section
    if not users:
        raise ValueError("No users provided")

    # Initialize counters
    stats = {"active": 0, "inactive": 0, "total": 0}  # highlighted line

    # Process each user
    for user in users:
        # Update statistics - highlighted section
        stats["total"] += 1
        if user.get("is_active", False):
            stats["active"] += 1
        else:
            stats["inactive"] += 1

    return stats

Range Highlighting

#!/bin/bash
# Setup script with highlighted sections
echo "Setting up development environment..."
export NODE_ENV=development
export API_URL=http://localhost:3000

# Install dependencies - highlighted section
npm install
pip install -r requirements.txt
poetry install

# Start services
docker-compose up -d
npm run dev

Code Annotations

Detailed Annotations

from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy.orm import Session
from typing import List

app = FastAPI(title="User API")  # (1)!

def get_db():  # (2)!
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/users/", response_model=List[UserResponse])  # (3)!
async def get_users(
    skip: int = 0,  # (4)!
    limit: int = 100,  # (5)!
    db: Session = Depends(get_db)  # (6)!
):
    """Retrieve a list of users with pagination."""
    users = db.query(User).offset(skip).limit(limit).all()  # (7)!
    return users

@app.post("/users/", response_model=UserResponse, status_code=201)
async def create_user(
    user: UserCreate,  # (8)!
    db: Session = Depends(get_db)
):
    """Create a new user."""
    db_user = User(**user.dict())  # (9)!
    db.add(db_user)
    db.commit()  # (10)!
    db.refresh(db_user)
    return db_user
  1. FastAPI application instance with custom title
  2. Database session dependency for connection management
  3. GET endpoint with automatic response model validation
  4. Number of records to skip for pagination
  5. Maximum number of records to return
  6. Dependency injection for database session
  7. SQLAlchemy query with offset and limit
  8. Pydantic model for user creation validation
  9. Convert Pydantic model to SQLAlchemy model
  10. Commit transaction to persist changes

Rich Annotations with Examples

version: '3.8'

services:
  web:
    build:
      context: .  # (1)!
      dockerfile: Dockerfile  # (2)!
    ports:
      - "8000:8000"  # (3)!
    environment:
      - DATABASE_URL=postgresql://user:pass@db:5432/app  # (4)!
      - REDIS_URL=redis://redis:6379  # (5)!
    depends_on:  # (6)!
      - db
      - redis
    volumes:
      - ./app:/app  # (7)!
    command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload  # (8)!

  db:
    image: postgres:14  # (9)!
    environment:
      POSTGRES_DB: app
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
    volumes:
      - postgres_data:/var/lib/postgresql/data  # (10)!

volumes:
  postgres_data:  # (11)!
  1. Build Context

    The . refers to the current directory as the build context. All files in this directory will be available during the Docker build process.

    # Example Dockerfile
    FROM python:3.9
    COPY . /app
    WORKDIR /app
    RUN pip install -r requirements.txt
    
  2. Custom Dockerfile

    Specify a custom Dockerfile name if not using the default Dockerfile:

    build:
      context: .
      dockerfile: Dockerfile.dev  # For development
    
  3. Port Mapping

    Maps host port 8000 to container port 8000. Make sure the host port is available:

    # Check if port is in use
    netstat -tlnp | grep 8000
    
  4. Database Connection

    PostgreSQL connection string format: postgresql://user:password@host:port/database

  5. Redis Configuration

    Redis connection for caching and session storage. Default port is 6379.

  6. Service Dependencies

    Ensures database and Redis start before the web service.

  7. Volume Mounting

    Mount local app directory for development hot reloading.

  8. Development Command

    --reload enables auto-restart on code changes.

  9. PostgreSQL Version

    Using PostgreSQL 14 for better performance and features.

  10. Data Persistence

    Named volume ensures database data persists between container restarts.

  11. Volume Declaration

    Declares the named volume at the top level.

Title Bars and File Names

API Endpoint Example

api/users.py
from fastapi import FastAPI, Query, Path
from pydantic import BaseModel
from typing import Optional, List
import uuid

app = FastAPI()

class User(BaseModel):
    id: str = None
    name: str
    email: str
    age: Optional[int] = None

@app.get("/users/{user_id}")
async def get_user(
    user_id: str = Path(..., description="The ID of the user to retrieve")
):
    """Get a specific user by ID."""
    # Implementation here
    pass

@app.get("/users/")
async def list_users(
    limit: int = Query(10, ge=1, le=100),
    offset: int = Query(0, ge=0)
):
    """List users with pagination."""
    # Implementation here
    pass

Configuration File

kubernetes/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-app
  labels:
    app: web-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web-app
  template:
    metadata:
      labels:
        app: web-app
    spec:
      containers:
      - name: web
        image: myapp:latest
        ports:
        - containerPort: 8000
        env:
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: db-secret
              key: url
        resources:
          requests:
            memory: "256Mi"
            cpu: "250m"
          limits:
            memory: "512Mi"
            cpu: "500m"

Database Schema

migrations/001_create_users.sql
-- Create users table with all necessary fields
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) UNIQUE NOT NULL,
    name VARCHAR(100) NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    is_active BOOLEAN DEFAULT true,
    is_verified BOOLEAN DEFAULT false,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Create index for email lookups
CREATE INDEX idx_users_email ON users(email);

-- Create index for active users
CREATE INDEX idx_users_active ON users(is_active) WHERE is_active = true;

-- Add trigger for updated_at
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ language 'plpgsql';

CREATE TRIGGER update_users_updated_at
    BEFORE UPDATE ON users
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();

Language-Specific Examples

Go

main.go
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/mux"
)

type User struct {
    ID    string `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

type UserHandler struct {
    users map[string]User
}

func (h *UserHandler) GetUser(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    userID := vars["id"]

    user, exists := h.users[userID]
    if !exists {
        http.Error(w, "User not found", http.StatusNotFound)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(user)
}

func main() {
    handler := &UserHandler{
        users: make(map[string]User),
    }

    r := mux.NewRouter()
    r.HandleFunc("/users/{id}", handler.GetUser).Methods("GET")

    fmt.Println("Server starting on :8080")
    log.Fatal(http.ListenAndServe(":8080", r))
}

Rust

src/main.rs
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

#[derive(Debug, Serialize, Deserialize, Clone)]
struct User {
    id: Uuid,
    name: String,
    email: String,
    active: bool,
}

struct UserService {
    users: HashMap<Uuid, User>,
}

impl UserService {
    fn new() -> Self {
        Self {
            users: HashMap::new(),
        }
    }

    fn create_user(&mut self, name: String, email: String) -> Result<User, String> {
        let user = User {
            id: Uuid::new_v4(),
            name,
            email,
            active: true,
        };

        self.users.insert(user.id, user.clone());
        Ok(user)
    }

    fn get_user(&self, id: &Uuid) -> Option<&User> {
        self.users.get(id)
    }

    fn list_active_users(&self) -> Vec<&User> {
        self.users
            .values()
            .filter(|user| user.active)
            .collect()
    }
}

fn main() {
    let mut service = UserService::new();

    match service.create_user("Alice".to_string(), "alice@example.com".to_string()) {
        Ok(user) => println!("Created user: {:?}", user),
        Err(e) => eprintln!("Error creating user: {}", e),
    }

    let active_users = service.list_active_users();
    println!("Active users: {}", active_users.len());
}

C++

user_manager.cpp
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
#include <memory>
#include <algorithm>

class User {
public:
    User(const std::string& id, const std::string& name, const std::string& email)
        : id_(id), name_(name), email_(email), active_(true) {}

    const std::string& getId() const { return id_; }
    const std::string& getName() const { return name_; }
    const std::string& getEmail() const { return email_; }
    bool isActive() const { return active_; }

    void setActive(bool active) { active_ = active; }

private:
    std::string id_;
    std::string name_;
    std::string email_;
    bool active_;
};

class UserManager {
public:
    void addUser(std::unique_ptr<User> user) {
        users_[user->getId()] = std::move(user);
    }

    User* getUser(const std::string& id) {
        auto it = users_.find(id);
        return (it != users_.end()) ? it->second.get() : nullptr;
    }

    std::vector<User*> getActiveUsers() {
        std::vector<User*> activeUsers;

        for (const auto& pair : users_) {
            if (pair.second->isActive()) {
                activeUsers.push_back(pair.second.get());
            }
        }

        return activeUsers;
    }

    size_t getUserCount() const {
        return users_.size();
    }

private:
    std::unordered_map<std::string, std::unique_ptr<User>> users_;
};

int main() {
    UserManager manager;

    // Add some users
    manager.addUser(std::make_unique<User>("1", "Alice", "alice@example.com"));
    manager.addUser(std::make_unique<User>("2", "Bob", "bob@example.com"));

    // Get active users
    auto activeUsers = manager.getActiveUsers();
    std::cout << "Active users: " << activeUsers.size() << std::endl;

    for (const auto& user : activeUsers) {
        std::cout << "- " << user->getName() << " (" << user->getEmail() << ")" << std::endl;
    }

    return 0;
}

Complex Examples

Multi-Language API Client

clients/python_client.py
import requests
from typing import Dict, List, Optional
import json

class APIClient:
    def __init__(self, base_url: str, api_key: str):
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        })

    def get_users(self, limit: int = 10, offset: int = 0) -> List[Dict]:
        """Fetch users with pagination."""
        response = self.session.get(
            f'{self.base_url}/users',
            params={'limit': limit, 'offset': offset}
        )
        response.raise_for_status()
        return response.json()

    def create_user(self, user_data: Dict) -> Dict:
        """Create a new user."""
        response = self.session.post(
            f'{self.base_url}/users',
            json=user_data
        )
        response.raise_for_status()
        return response.json()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.session.close()

# Usage example
with APIClient('https://api.example.com', 'your-api-key') as client:
    users = client.get_users(limit=5)
    print(f"Found {len(users)} users")
clients/js_client.js
class APIClient {
    constructor(baseUrl, apiKey) {
        this.baseUrl = baseUrl.replace(/\/$/, '');
        this.headers = {
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json'
        };
    }

    async getUsers(limit = 10, offset = 0) {
        const url = new URL(`${this.baseUrl}/users`);
        url.searchParams.append('limit', limit);
        url.searchParams.append('offset', offset);

        const response = await fetch(url, {
            method: 'GET',
            headers: this.headers
        });

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        return await response.json();
    }

    async createUser(userData) {
        const response = await fetch(`${this.baseUrl}/users`, {
            method: 'POST',
            headers: this.headers,
            body: JSON.stringify(userData)
        });

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        return await response.json();
    }
}

// Usage example
const client = new APIClient('https://api.example.com', 'your-api-key');

try {
    const users = await client.getUsers(5);
    console.log(`Found ${users.length} users`);
} catch (error) {
    console.error('Error fetching users:', error.message);
}
api_examples.sh
#!/bin/bash

# Configuration
API_BASE="https://api.example.com"
API_KEY="your-api-key"

# Common headers
AUTH_HEADER="Authorization: Bearer $API_KEY"
CONTENT_TYPE="Content-Type: application/json"

# Get users with pagination
echo "Fetching users..."
curl -s \
  -H "$AUTH_HEADER" \
  -H "$CONTENT_TYPE" \
  "$API_BASE/users?limit=5&offset=0" \
  | jq '.'

# Create a new user
echo "Creating new user..."
curl -s \
  -X POST \
  -H "$AUTH_HEADER" \
  -H "$CONTENT_TYPE" \
  -d '{
    "name": "John Doe",
    "email": "john.doe@example.com",
    "role": "user"
  }' \
  "$API_BASE/users" \
  | jq '.'

# Get specific user
echo "Fetching specific user..."
USER_ID="123"
curl -s \
  -H "$AUTH_HEADER" \
  -H "$CONTENT_TYPE" \
  "$API_BASE/users/$USER_ID" \
  | jq '.'

# Update user
echo "Updating user..."
curl -s \
  -X PUT \
  -H "$AUTH_HEADER" \
  -H "$CONTENT_TYPE" \
  -d '{
    "name": "John Smith",
    "email": "john.smith@example.com"
  }' \
  "$API_BASE/users/$USER_ID" \
  | jq '.'

Interactive Features

All code blocks in this documentation include:

  • Copy Button - Click the copy icon to copy code to clipboard
  • Syntax Highlighting - Language-specific color coding
  • Line Numbers - Optional line numbering for reference
  • Line Highlighting - Emphasize important lines
  • Annotations - Detailed explanations with rich content
  • Title Bars - File names and descriptions
  • Mobile Responsive - Horizontal scrolling on small screens

Best Practices Demonstrated

  1. Language Specification - Every code block specifies its language
  2. Meaningful Examples - Real-world, runnable code examples
  3. Progressive Complexity - From simple to advanced examples
  4. Consistent Formatting - Standard indentation and style
  5. Comprehensive Comments - Detailed inline documentation
  6. Error Handling - Proper exception and error management
  7. Type Hints - Modern type annotation practices
  8. Security Considerations - Safe coding practices shown