Samples

Code Blocks

This page shows a fenced code block for each common language, for checking syntax highlighting in light and dark mode.

Web

PHP

PHP
 1<?php
 2
 3namespace App\Http\Controllers;
 4
 5use App\Models\Post;
 6use Illuminate\Http\Request;
 7
 8class PostController extends Controller
 9{
10    public function index(Request $request): array
11    {
12        $posts = Post::query()
13            ->where('published', true)
14            ->latest()
15            ->paginate(15);
16
17        return ['data' => $posts, 'total' => $posts->total()];
18    }
19}

Blade

Blade
 1@extends('layouts.app')
 2
 3@section('content')
 4    <h1>{{ $title }}</h1>
 5
 6    @forelse ($posts as $post)
 7        <x-post-card :post="$post" wire:key="post-{{ $post->id }}" />
 8    @empty
 9        <p>No posts yet.</p>
10    @endforelse
11@endsection

HTML

HTML
 1<!DOCTYPE html>
 2<html lang="en">
 3  <head>
 4    <meta charset="utf-8">
 5    <title>Sample</title>
 6    <link rel="stylesheet" href="/app.css">
 7  </head>
 8  <body>
 9    <main id="app" class="container">
10      <button type="button" data-action="save">Save</button>
11    </main>
12  </body>
13</html>

CSS

CSS
 1:root {
 2  --brand: #ff2d20;
 3  --radius: 0.5rem;
 4}
 5
 6.button {
 7  display: inline-flex;
 8  padding: 0.5rem 1rem;
 9  border-radius: var(--radius);
10  background: var(--brand);
11}
12
13@media (prefers-color-scheme: dark) {
14  .button:hover { filter: brightness(1.2); }
15}

SCSS

SCSS
 1$spacing: 1rem;
 2
 3.card {
 4  padding: $spacing;
 5
 6  &__title {
 7    font-weight: 600;
 8  }
 9
10  &:hover {
11    box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
12  }
13}

JavaScript

JavaScript
 1import { debounce } from './utils.js';
 2
 3export async function search(query) {
 4  const response = await fetch(`/search?q=${encodeURIComponent(query)}`);
 5
 6  if (!response.ok) {
 7    throw new Error(`Search failed: ${response.status}`);
 8  }
 9
10  return (await response.json()).map(({ title, url }) => ({ title, url }));
11}
12
13document.querySelector('#search')?.addEventListener('input', debounce((event) => search(event.target.value), 200));

TypeScript

TypeScript
 1interface User {
 2  id: number;
 3  name: string;
 4  email?: string;
 5}
 6
 7type Role = 'admin' | 'editor' | 'viewer';
 8
 9export function greet<T extends User>(user: T, role: Role = 'viewer'): string {
10  return `Hello, ${user.name} (${role})`;
11}

JSX

JSX
 1export default function TodoList({ items, onToggle }) {
 2  return (
 3    <ul className="todos">
 4      {items.map((item) => (
 5        <li key={item.id} onClick={() => onToggle(item.id)}>
 6          {item.done ? <s>{item.title}</s> : item.title}
 7        </li>
 8      ))}
 9    </ul>
10  );
11}

TSX

TSX
 1type Props = { label: string; count: number; onIncrement: () => void };
 2
 3export function Counter({ label, count, onIncrement }: Props) {
 4  return (
 5    <button type="button" onClick={onIncrement}>
 6      {label}: {count}
 7    </button>
 8  );
 9}

Vue

vue
 1<script setup>
 2import { ref, computed } from 'vue'
 3
 4const count = ref(0)
 5const doubled = computed(() => count.value * 2)
 6</script>
 7
 8<template>
 9  <button @click="count++">Count is {{ count }} (doubled: {{ doubled }})</button>
10</template>
11
12<style scoped>
13button { font-weight: bold; }
14</style>

Scripting

Python

Python
 1from dataclasses import dataclass
 2from typing import Iterable
 3
 4
 5@dataclass
 6class Item:
 7    name: str
 8    price: float
 9
10
11def total(items: Iterable[Item], tax: float = 0.1) -> float:
12    """Return the total price including tax."""
13    subtotal = sum(item.price for item in items)
14    return round(subtotal * (1 + tax), 2)
15
16
17if __name__ == "__main__":
18    print(total([Item("book", 12.5), Item("pen", 1.2)]))

Ruby

Ruby
 1class Greeter
 2  attr_reader :name
 3
 4  def initialize(name)
 5    @name = name
 6  end
 7
 8  def greet(times: 1)
 9    times.times.map { |i| "Hello, #{name}! (#{i + 1})" }
10  end
11end
12
13puts Greeter.new("Ruby").greet(times: 2)

Systems and Apps

Go

Go
 1package main
 2
 3import (
 4	"fmt"
 5	"net/http"
 6)
 7
 8func handler(w http.ResponseWriter, r *http.Request) {
 9	fmt.Fprintf(w, "Hello, %s!", r.URL.Query().Get("name"))
10}
11
12func main() {
13	http.HandleFunc("/", handler)
14	if err := http.ListenAndServe(":8080", nil); err != nil {
15		panic(err)
16	}
17}

Rust

Rust
 1use std::collections::HashMap;
 2
 3#[derive(Debug)]
 4struct Counter {
 5    words: HashMap<String, usize>,
 6}
 7
 8impl Counter {
 9    fn count(text: &str) -> Self {
10        let mut words = HashMap::new();
11        for word in text.split_whitespace() {
12            *words.entry(word.to_lowercase()).or_insert(0) += 1;
13        }
14        Counter { words }
15    }
16}
17
18fn main() {
19    println!("{:?}", Counter::count("the quick brown fox jumps over the lazy dog"));
20}

Java

Java
 1import java.util.List;
 2import java.util.stream.Collectors;
 3
 4public final class Names {
 5    private Names() {}
 6
 7    public static List<String> upper(List<String> names) {
 8        return names.stream()
 9            .filter(name -> !name.isBlank())
10            .map(String::toUpperCase)
11            .collect(Collectors.toList());
12    }
13}

Kotlin

kotlin
 1data class Book(val title: String, val year: Int)
 2
 3fun main() {
 4    val books = listOf(Book("Dune", 1965), Book("Neuromancer", 1984))
 5    books
 6        .filter { it.year > 1970 }
 7        .forEach { println("${it.title} (${it.year})") }
 8}

Swift

Swift
 1import Foundation
 2
 3struct Weather: Codable {
 4    let city: String
 5    let temperature: Double
 6}
 7
 8func describe(_ weather: Weather) -> String {
 9    let rounded = String(format: "%.1f", weather.temperature)
10    return "\(weather.city): \(rounded)°C"
11}
12
13print(describe(Weather(city: "Seoul", temperature: 21.37)))

C

C
 1#include <stdio.h>
 2#include <stdlib.h>
 3
 4int main(void) {
 5    int *numbers = malloc(5 * sizeof(int));
 6    if (numbers == NULL) {
 7        return 1;
 8    }
 9
10    for (int i = 0; i < 5; i++) {
11        numbers[i] = i * i;
12        printf("%d\n", numbers[i]);
13    }
14
15    free(numbers);
16    return 0;
17}

C++

C++
 1#include <iostream>
 2#include <vector>
 3#include <algorithm>
 4
 5template <typename T>
 6T largest(const std::vector<T>& values) {
 7    return *std::max_element(values.begin(), values.end());
 8}
 9
10int main() {
11    std::vector<int> values{3, 1, 4, 1, 5, 9};
12    std::cout << "Largest: " << largest(values) << std::endl;
13}

C#

C#
 1using System;
 2using System.Linq;
 3
 4public record Order(int Id, decimal Amount);
 5
 6public static class Program
 7{
 8    public static void Main()
 9    {
10        var orders = new[] { new Order(1, 9.99m), new Order(2, 24.50m) };
11        var total = orders.Sum(o => o.Amount);
12        Console.WriteLine($"Total: {total:C}");
13    }
14}

Dart

Dart
 1class Point {
 2  final double x;
 3  final double y;
 4
 5  const Point(this.x, this.y);
 6
 7  Point operator +(Point other) => Point(x + other.x, y + other.y);
 8
 9  @override
10  String toString() => 'Point($x, $y)';
11}
12
13void main() {
14  print(const Point(1, 2) + const Point(3, 4));
15}

Data and Configuration

SQL

SQL
 1SELECT u.id, u.name, COUNT(p.id) AS post_count
 2FROM users AS u
 3LEFT JOIN posts AS p ON p.user_id = u.id AND p.published_at IS NOT NULL
 4WHERE u.created_at >= '2026-01-01'
 5GROUP BY u.id, u.name
 6HAVING COUNT(p.id) > 3
 7ORDER BY post_count DESC
 8LIMIT 10;

JSON

JSON
 1{
 2  "name": "document2-test-docs",
 3  "private": false,
 4  "versions": ["master", "12.x", "5.8"],
 5  "settings": {
 6    "search": true,
 7    "maxResults": 20,
 8    "theme": null
 9  }
10}

YAML

YAML
 1name: ci
 2
 3on:
 4  push:
 5    branches: [main]
 6
 7jobs:
 8  test:
 9    runs-on: ubuntu-latest
10    steps:
11      - uses: actions/checkout@v4
12      - run: composer install --no-interaction
13      - run: vendor/bin/pest

TOML

TOML
 1[package]
 2name = "sample"
 3version = "0.1.0"
 4edition = "2021"
 5
 6[dependencies]
 7serde = { version = "1.0", features = ["derive"] }
 8tokio = { version = "1", features = ["full"] }

XML

XML
 1<?xml version="1.0" encoding="UTF-8"?>
 2<phpunit bootstrap="vendor/autoload.php" colors="true">
 3    <testsuites>
 4        <testsuite name="Feature">
 5            <directory>tests/Feature</directory>
 6        </testsuite>
 7    </testsuites>
 8</phpunit>

INI

INI
 1; Application settings
 2[app]
 3name = Sample
 4debug = false
 5
 6[database]
 7host = 127.0.0.1
 8port = 3306

GraphQL

GraphQL
 1query RecentPosts($first: Int = 10) {
 2  posts(first: $first, orderBy: { field: CREATED_AT, direction: DESC }) {
 3    nodes {
 4      id
 5      title
 6      author { name }
 7    }
 8  }
 9}

Shell and Tooling

Bash

Shell
 1#!/usr/bin/env bash
 2set -euo pipefail
 3
 4for file in docs/*.md; do
 5  if grep -q "TODO" "$file"; then
 6    echo "Found TODO in ${file}"
 7  fi
 8done
 9
10export APP_ENV="${APP_ENV:-local}"

Console session

Shell Session
 1$ composer create-project laravel/laravel example
 2$ cd example
 3$ php artisan serve
 4   INFO  Server running on [http://127.0.0.1:8000].

PowerShell

PowerShell
 1$files = Get-ChildItem -Path .\docs -Filter *.md -Recurse
 2
 3foreach ($file in $files) {
 4    $lines = (Get-Content $file.FullName).Count
 5    Write-Output "$($file.Name): $lines lines"
 6}

Dockerfile

Dockerfile
 1FROM php:8.4-fpm-alpine
 2
 3WORKDIR /var/www/html
 4
 5RUN apk add --no-cache git unzip \
 6    && docker-php-ext-install pdo_mysql
 7
 8COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
 9COPY . .
10
11RUN composer install --no-dev --optimize-autoloader
12
13CMD ["php-fpm"]

Nginx

Nginx
 1server {
 2    listen 80;
 3    server_name example.test;
 4    root /var/www/html/public;
 5
 6    location / {
 7        try_files $uri $uri/ /index.php?$query_string;
 8    }
 9
10    location ~ \.php$ {
11        fastcgi_pass 127.0.0.1:9000;
12        include fastcgi_params;
13    }
14}

Makefile

Makefile
 1.PHONY: test lint
 2
 3test:
 4	vendor/bin/pest
 5
 6lint:
 7	vendor/bin/pint --test

Diff

Diff
 1 public function handle(): void
 2 {
 3-    $this->info('Done');
 4+    $this->components->info('Done');
 5+    $this->newLine();
 6 }

Markdown

Markdown
 1# Title
 2
 3Some **bold** and _italic_ text with a [link](https://example.com).
 4
 5- First item
 6- Second item

Tabs

Adjacent code blocks with tab=<name> are shown as one block with a tab for each.

Two tabs:

JavaScript
 1export function greet(name) {
 2    return `Hello, ${name}!`;
 3}
TypeScript
 1export function greet(name: string): string {
 2    return `Hello, ${name}!`;
 3}

Three tabs:

Shell
 1npm install laravel-echo pusher-js
Shell
 1yarn add laravel-echo pusher-js
Shell
 1pnpm add laravel-echo pusher-js

Choosing a tab above also switches this group, because it has the same tab names, and the choice is remembered on other pages:

JavaScript
 1greet('Taylor');
TypeScript
 1greet('Taylor' as string);

Edge Cases

No language

 1This block has no language, so it is not highlighted.
 2    Indentation inside it is kept.

Plain text

txt
 1Plain text marked as text.

Long lines

PHP
 1$message = 'This line is intentionally very long so that the code block has to scroll horizontally instead of wrapping, which is how long lines should behave in documentation code samples.';

Indented code block

$indented = 'Four spaces of indentation make a code block too.';

Inline code

Run php artisan migrate to create the tables, then call Route::get('/', fn () => view('welcome')) in routes/web.php.