Code Examples¶
This page demonstrates all the code highlighting features available in Material for MkDocs.
Basic Syntax Highlighting¶
Just specify the language after the triple backticks:
Code with Line Numbers¶
Add linenums="1" to show line numbers:
def bubble_sort(items):
for i in range(len(items)):
for j in range(len(items) - 1 - i):
if items[j] > items[j + 1]:
items[j], items[j + 1] = items[j + 1], items[j]
return items
Highlighting Specific Lines¶
Use hl_lines to emphasize important lines:
def bubble_sort(items):
for i in range(len(items)):
for j in range(len(items) - 1 - i):
if items[j] > items[j + 1]:
items[j], items[j + 1] = items[j + 1], items[j]
return items
You can also highlight ranges:
def bubble_sort(items):
for i in range(len(items)):
for j in range(len(items) - 1 - i):
if items[j] > items[j + 1]:
items[j], items[j + 1] = items[j + 1], items[j]
return items
Code Blocks with Titles¶
Add a title to show the filename or description:
bubble_sort.py
def bubble_sort(items):
"""Sort a list using bubble sort algorithm."""
for i in range(len(items)):
for j in range(len(items) - 1 - i):
if items[j] > items[j + 1]:
items[j], items[j + 1] = items[j + 1], items[j]
return items
mkdocs.yml
site_name: My Documentation
theme:
name: material
features:
- content.code.copy
- content.code.annotate
Code with Annotations¶
Add explanatory annotations to your code (hover over the numbers):
def connect_to_database(host, port): # (1)!
"""Connect to the database."""
connection = create_connection(
host=host, # (2)!
port=port,
timeout=30 # (3)!
)
return connection
- Main function that establishes database connection
- Database server hostname or IP address
- Connection timeout in seconds - increase for slower networks
Inline Code Highlighting¶
You can use inline code with syntax highlighting: range() and const x = 42;
For example, the print() function in Python or console.log() in JavaScript.
Complete Example - All Features Combined¶
api_handler.py
import requests
from typing import Dict, Any
class APIHandler:
"""Handle API requests with proper error handling."""
def __init__(self, base_url: str, api_key: str): # (1)!
self.base_url = base_url
self.api_key = api_key
self.session = requests.Session() # (2)!
def get(self, endpoint: str) -> Dict[str, Any]:
"""Make a GET request to the API."""
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
response = self.session.get( # (3)!
f"{self.base_url}/{endpoint}",
headers=headers,
timeout=30
)
response.raise_for_status()
return response.json()
- Initialize the API handler with base URL and authentication key
- Use a session for connection pooling and better performance
- Make the actual HTTP GET request with proper headers and timeout
Different Languages¶
JavaScript/TypeScript¶
user.service.ts
interface User {
id: number;
name: string;
email: string;
}
class UserService {
async getUser(id: number): Promise<User> {
const response = await fetch(`/api/users/${id}`);
return await response.json();
}
}
Go¶
main.go
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
Bash/Shell¶
deploy.sh
#!/bin/bash
# Build the Docker image
docker build -t myapp:latest .
# Stop and remove old container
docker stop myapp || true
docker rm myapp || true
# Run the new container
docker run -d \
--name myapp \
-p 8000:8000 \
--restart unless-stopped \
myapp:latest
SQL¶
schema.sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
username VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_username ON users(username);
JSON with Syntax Highlighting¶
config.json
{
"name": "egygeeks-docs",
"version": "1.0.0",
"server": {
"host": "50.3.85.110",
"port": 80,
"ssl": false
},
"features": {
"authentication": true,
"analytics": true
}
}
YAML Configuration¶
docker-compose.yml
version: '3.8'
services:
web:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
restart: unless-stopped
app:
build: .
environment:
- DATABASE_URL=postgresql://user:pass@db:5432/mydb
depends_on:
- db
db:
image: postgres:15
environment:
POSTGRES_DB: mydb
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata: