Code Block
Syntax-highlighted code rendered server-side with Chroma. It follows the active theme, includes an accessible copy button, and falls back to plain text when a lexer is unknown.
package main
import "fmt"
func main() {
fmt.Println("hello, world")
}@codeblock.CodeBlock(codeblock.Config{
Language: "go",
Label: "Hello",
Code: `package main
func main() {
fmt.Println("hello, world")
}`,
})HTML
Use Language: "html" for templates, fragments, and Alpine/HTMX snippets.
<button x-data="{ open: false }" @click="open = !open" class="btn">Toggle</button>@codeblock.CodeBlock(codeblock.Config{
Language: "html",
Code: `<button x-data="{open:false}" @click="open=!open" class="btn">Toggle</button>`,
})CSS
CSS snippets use the same highlighted shell, so theme token examples stay readable in light and dark mode.
.btn {
color: var(--color-primary);
padding: 0.5rem 1rem;
border-radius: 0.375rem;
}@codeblock.CodeBlock(codeblock.Config{
Language: "css",
Code: `.btn { color: var(--color-primary); padding: 0.5rem 1rem; }`,
})Bash
Command snippets can set a short Label when the language name is not specific enough.
go get github.com/a-h/templ
npm install -D tailwindcss@latest@codeblock.CodeBlock(codeblock.Config{
Language: "bash",
Label: "Install",
Code: "go get github.com/a-h/templ",
})Scrollable
Set MaxHeight for long snippets that should scroll inside the code panel instead of pushing the page apart.
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello")
})
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "ok")
})
http.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "v1.0.0")
})
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}@codeblock.CodeBlock(codeblock.Config{
Language: "go",
MaxHeight: "180px",
Code: longGoSnippet,
})API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
Language | string | "" | Chroma lexer key such as "go", "css", "html", or "bash"; "templ" aliases to Go and unknown values render as plain text. |
Code | string | "" | Source code to display and copy. |
Label | string | Language | Header label; defaults to the resolved language when empty. |
MaxHeight | string | "" | Optional CSS max-height such as "300px"; enables vertical scrolling inside the code body. |
ID | string | auto | Optional code element id; otherwise generated from the label, language, and code content for copy-button targeting. |