Code
Code displays a code block with optional syntax highlighting and copy functionality
TailwindCSS
fmt.Println("Hello, World!")
package showcase
import "github.com/axzilla/templui/component/code"
templ CodeDefault() {
<div class="w-full max-w-md">
@code.Code(code.Props{
Language: "go",
}) {
{ `fmt.Println("Hello, World!")` }
}
</div>
}
package code
import (
"github.com/axzilla/templui/icon"
"github.com/axzilla/templui/util"
)
type Size string
const (
SizeSm Size = "sm"
SizeLg Size = "lg"
SizeFull Size = "full"
)
type Props struct {
ID string
Class string
Attrs templ.Attributes
Language string
ShowCopyButton bool
Size Size
CodeClass string
}
templ Code(props ...Props) {
{{ var p Props }}
if len(props) > 0 {
{{ p = props[0] }}
}
if p.ID == "" {
{{ p.ID = util.RandomID() }}
}
<div
id={ p.ID }
class={ util.TwMerge("relative", p.Class) }
{ p.Attrs... }
x-data="code"
>
<pre class="overflow-hidden!">
<code
x-ref="code"
class={
util.TwMerge(
"language-"+p.Language,
"overflow-y-auto! rounded-md block text-sm max-h-[501px]!",
util.If(p.Size == SizeSm, "max-h-[250px]!"),
util.If(p.Size == SizeLg, "max-h-[1000px]!"),
util.If(p.Size == SizeFull, "max-h-full!"),
"hljs-target",
p.CodeClass,
),
}
>
{ children... }
</code>
</pre>
if p.ShowCopyButton {
<button
class="absolute top-2 right-2 hover:bg-gray-500 hover:bg-opacity-30 text-white p-2 rounded"
@click="copyCode"
>
<span x-show="isCopied">
@icon.Check(icon.Props{Size: 14})
</span>
<span x-show="isNotCopied">
@icon.Clipboard(icon.Props{Size: 14})
</span>
</button>
}
</div>
}
templ Script() {
{{ handle := templ.NewOnceHandle() }}
@handle.Once() {
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/pojoaque.min.css"/>
<script nonce={ templ.GetNonce(ctx) } src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script nonce={ templ.GetNonce(ctx) }>
document.addEventListener('alpine:init', () => {
document.querySelectorAll('code.hljs-target').forEach((block) => {
try {
hljs.highlightElement(block);
} catch (error) {
console.error("Highlight.js error on element:", error, block);
}
});
Alpine.data('code', () => ({
isCopied: false,
isNotCopied: true,
copyCode() {
try {
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(this.$refs.code.textContent);
} else {
const textArea = document.createElement('textarea');
textArea.value = this.$refs.code.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
this.isCopied = true;
this.isNotCopied = false;
setTimeout(() => {
this.isCopied = false;
this.isNotCopied = true;
}, 2000);
} catch (err) {
console.error('Copy failed', err);
}
}
}))
})
</script>
}
}
Usage
1. Add the script to your page/layout:
// Option A: All components (recommended)
@util.ComponentScripts()
// Option B: Only Code
@code.Script()
Examples
Copy Button
fmt.Println("Hello, World!")
package showcase
import "github.com/axzilla/templui/component/code"
templ CodeCopyButton() {
<div class="w-full max-w-md">
@code.Code(code.Props{
Language: "go",
ShowCopyButton: true,
}) {
{ `fmt.Println("Hello, World!")` }
}
</div>
}
Custom Size
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
fmt.Println("Server starting on :3000...")
if err := http.ListenAndServe(":3000", nil); err != nil {
log.Fatal(err)
}
}
package showcase
import "github.com/axzilla/templui/component/code"
templ CodeCustomSize() {
<div class="w-full max-w-md">
@code.Code(code.Props{
Language: "go",
ShowCopyButton: true,
Size: code.SizeSm,
}) {
{ `package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
fmt.Println("Server starting on :3000...")
if err := http.ListenAndServe(":3000", nil); err != nil {
log.Fatal(err)
}
}` }
}
</div>
}