templ

package module
v0.3.960 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2025 License: MIT Imports: 24 Imported by: 4,629

README ΒΆ

templ

An HTML templating language for Go that has great developer tooling.

templ

Documentation

See user documentation at https://templ.guide

Go Reference xc compatible Go Coverage Go Report Card

Tasks

version-set

Set the version of templ to the current version.

version set --template="0.3.%d"

build

Build a local version.

version set --template="0.3.%d"
cd cmd/templ
go build

install-snapshot

Build and install current version.

# Remove templ from the non-standard ~/bin/templ path
# that this command previously used.
rm -f ~/bin/templ
# Clear LSP logs.
rm -f cmd/templ/lspcmd/*.txt
# Update version.
version set --template="0.3.%d"
# Install to $GOPATH/bin or $HOME/go/bin
cd cmd/templ && go install

build-snapshot

Use goreleaser to build the command line binary using goreleaser.

goreleaser build --snapshot --clean

generate

Run templ generate using local version.

go run ./cmd/templ generate -include-version=false

test

Run Go tests.

version set --template="0.3.%d"
go run ./cmd/templ generate -include-version=false
go test ./...

test-short

Run Go tests.

version set --template="0.3.%d"
go run ./cmd/templ generate -include-version=false
go test ./... -short

test-cover

Run Go tests.

# Create test profile directories.
mkdir -p coverage/fmt
mkdir -p coverage/generate
mkdir -p coverage/version
mkdir -p coverage/unit
# Build the test binary.
go build -cover -o ./coverage/templ-cover ./cmd/templ
# Run the covered generate command.
GOCOVERDIR=coverage/fmt ./coverage/templ-cover fmt .
GOCOVERDIR=coverage/generate ./coverage/templ-cover generate -include-version=false
GOCOVERDIR=coverage/version ./coverage/templ-cover version
# Run the unit tests.
go test -cover ./... -coverpkg ./... -args -test.gocoverdir="$PWD/coverage/unit"
# Display the combined percentage.
go tool covdata percent -i=./coverage/fmt,./coverage/generate,./coverage/version,./coverage/unit
# Generate a text coverage profile for tooling to use.
go tool covdata textfmt -i=./coverage/fmt,./coverage/generate,./coverage/version,./coverage/unit -o coverage.out
# Print total
go tool cover -func coverage.out | grep total

test-cover-watch

interactive: true

gotestsum --watch -- -coverprofile=coverage.out

test-fuzz

./parser/v2/fuzz.sh
./parser/v2/goexpression/fuzz.sh

benchmark

Run benchmarks.

go run ./cmd/templ generate -include-version=false && go test ./... -bench=. -benchmem

fmt

Format all Go and templ code.

gofmt -s -w .
go run ./cmd/templ fmt .

lint

Run the lint operations that are run as part of the CI.

golangci-lint run --verbose

ensure-generated

Ensure that templ files have been generated with the local version of templ, and that those files have been added to git.

Requires: generate

git diff --exit-code

push-release-tag

Push a semantic version number to GitHub to trigger the release process.

version push --template="0.3.%d" --prefix="v"

docs-run

Run the development server.

Directory: docs

npm run start

docs-build

Build production docs site.

Directory: docs

npm run build

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const FailedSanitizationURL = SafeURL("about:invalid#TemplFailedSanitizationURL")

FailedSanitizationURL is returned if a URL fails sanitization checks.

Variables ΒΆ

View Source
var NopComponent = ComponentFunc(func(ctx context.Context, w io.Writer) error { return nil })

NopComponent is a component that doesn't render anything.

Functions ΒΆ

func Bool ΒΆ added in v0.0.139

func Bool(value bool) bool

Bool attribute value.

func CSSID ΒΆ added in v0.0.113

func CSSID(name string, css string) string

CSSID calculates an ID.

func ClearChildren ΒΆ added in v0.2.184

func ClearChildren(ctx context.Context) context.Context

func EscapeString ΒΆ

func EscapeString[T ~string](s T) string

EscapeString escapes HTML text within templates.

func GetBuffer ΒΆ added in v0.2.194

func GetBuffer() *bytes.Buffer

func GetNonce ΒΆ added in v0.2.707

func GetNonce(ctx context.Context) (nonce string)

GetNonce returns the CSP nonce value set with WithNonce, or an empty string if none has been set.

func InitializeContext ΒΆ added in v0.2.184

func InitializeContext(ctx context.Context) context.Context

InitializeContext initializes context used to store internal state used during rendering.

func JSONString ΒΆ added in v0.2.707

func JSONString(v any) (string, error)

JSONString returns a JSON encoded string of v.

func JoinStringErrs ΒΆ added in v0.2.501

func JoinStringErrs[T stringable](s T, errs ...error) (string, error)

JoinStringErrs joins an optional list of errors.

func ReleaseBuffer ΒΆ added in v0.2.194

func ReleaseBuffer(b *bytes.Buffer)

func RenderAttributes ΒΆ added in v0.2.501

func RenderAttributes(ctx context.Context, w io.Writer, attributes Attributer) (err error)

func RenderCSSItems ΒΆ added in v0.2.184

func RenderCSSItems(ctx context.Context, w io.Writer, classes ...any) (err error)

RenderCSSItems renders the CSS to the writer, if the items haven't already been rendered.

func RenderFragments ΒΆ added in v0.3.920

func RenderFragments(ctx context.Context, w io.Writer, c Component, ids ...any) error

RenderFragments renders the specified fragments to w.

func RenderScriptItems ΒΆ added in v0.2.184

func RenderScriptItems(ctx context.Context, w io.Writer, scripts ...ComponentScript) (err error)

RenderScriptItems renders a <script> element, if the script has not already been rendered.

func SafeScript ΒΆ added in v0.0.139

func SafeScript(functionName string, params ...any) string

SafeScript encodes unknown parameters for safety for inside HTML attributes.

func SafeScriptInline ΒΆ added in v0.2.476

func SafeScriptInline(functionName string, params ...any) string

SafeScript encodes unknown parameters for safety for inline scripts.

func ToGoHTML ΒΆ added in v0.2.501

func ToGoHTML(ctx context.Context, c Component) (s template.HTML, err error)

ToGoHTML renders the component to a Go html/template template.HTML string.

func Version ΒΆ added in v0.2.171

func Version() string

func WithChildren ΒΆ added in v0.2.184

func WithChildren(ctx context.Context, children Component) context.Context

func WithContentType ΒΆ added in v0.0.148

func WithContentType(contentType string) func(*ComponentHandler)

WithContentType sets the Content-Type header returned by the ComponentHandler.

func WithErrorHandler ΒΆ added in v0.0.139

func WithErrorHandler(eh func(r *http.Request, err error) http.Handler) func(*ComponentHandler)

WithErrorHandler sets the error handler used if rendering fails.

func WithFragments ΒΆ added in v0.3.920

func WithFragments(ids ...any) func(*ComponentHandler)

WithFragments sets the ids of the fragments to render. If not set, all content is rendered.

func WithNonce ΒΆ added in v0.2.707

func WithNonce(ctx context.Context, nonce string) context.Context

WithNonce sets a CSP nonce on the context and returns it.

func WithStatus ΒΆ added in v0.0.139

func WithStatus(status int) func(*ComponentHandler)

WithStatus sets the HTTP status code returned by the ComponentHandler.

func WithStreaming ΒΆ added in v0.2.731

func WithStreaming() func(*ComponentHandler)

WithStreaming sets the ComponentHandler to stream the response instead of buffering it.

func WriteWatchModeString deprecated added in v0.2.542

func WriteWatchModeString(w io.Writer, lineNum int) error

WriteWatchModeString is used when rendering templates in development mode. the generator would have written non-go code to the _templ.txt file, which is then read by this function and written to the output.

Deprecated: since templ v0.3.x generated code uses WriteString.

Types ΒΆ

type Attributer ΒΆ added in v0.3.865

type Attributer interface {
	Items() []KeyValue[string, any]
}

type Attributes ΒΆ added in v0.2.501

type Attributes map[string]any

Attributes is an alias to map[string]any made for spread attributes.

func (Attributes) Items ΒΆ added in v0.3.865

func (a Attributes) Items() []KeyValue[string, any]

Returns the items of the attributes map in key sorted order.

type CSSClass ΒΆ added in v0.0.113

type CSSClass interface {
	ClassName() string
}

CSSClass provides a class name.

func Class ΒΆ added in v0.0.113

func Class(name string) CSSClass

Class returns a CSS class name. Deprecated: use a string instead.

func SafeClass ΒΆ added in v0.0.139

func SafeClass(name string) CSSClass

SafeClass bypasses CSS class name validation. Deprecated: use a string instead.

type CSSClasses ΒΆ added in v0.0.113

type CSSClasses []any

CSSClasses is a slice of CSS classes.

func Classes ΒΆ added in v0.0.113

func Classes(classes ...any) CSSClasses

Classes for CSS. Supported types are string, ConstantCSSClass, ComponentCSSClass, map[string]bool.

func (CSSClasses) String ΒΆ added in v0.0.113

func (classes CSSClasses) String() string

String returns the names of all CSS classes.

type CSSHandler ΒΆ added in v0.0.113

type CSSHandler struct {
	Logger  func(err error)
	Classes []ComponentCSSClass
}

CSSHandler is a HTTP handler that serves CSS.

func NewCSSHandler ΒΆ added in v0.0.113

func NewCSSHandler(classes ...CSSClass) CSSHandler

NewCSSHandler creates a handler that serves a stylesheet containing the CSS of the classes passed in. This is used by the CSSMiddleware to provide global stylesheets for templ components.

func (CSSHandler) ServeHTTP ΒΆ added in v0.0.113

func (cssh CSSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type CSSMiddleware ΒΆ added in v0.0.113

type CSSMiddleware struct {
	Path       string
	CSSHandler CSSHandler
	Next       http.Handler
}

CSSMiddleware renders a global stylesheet.

func NewCSSMiddleware ΒΆ added in v0.0.113

func NewCSSMiddleware(next http.Handler, classes ...CSSClass) CSSMiddleware

NewCSSMiddleware creates HTTP middleware that renders a global stylesheet of ComponentCSSClass CSS if the request path matches, or updates the HTTP context to ensure that any handlers that use templ.Components skip rendering <style> elements for classes that are included in the global stylesheet. By default, the stylesheet path is /styles/templ.css

func (CSSMiddleware) ServeHTTP ΒΆ added in v0.0.113

func (cssm CSSMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Component ΒΆ

type Component interface {
	// Render the template.
	Render(ctx context.Context, w io.Writer) error
}

Component is the interface that all templates implement.

func Fragment ΒΆ added in v0.3.920

func Fragment(id any) Component

Fragment defines a fragment within a template that can be rendered conditionally based on the id. You can use it to render a specific part of a page, e.g. to reduce the amount of HTML returned from a HTMX-initiated request. Any non-matching contents of the template are rendered, but discarded by the FramentWriter.

func FromGoHTML ΒΆ added in v0.2.501

func FromGoHTML(t *template.Template, data any) Component

FromGoHTML creates a templ Component from a Go html/template template.

func GetChildren ΒΆ added in v0.2.184

func GetChildren(ctx context.Context) Component

GetChildren from the context.

func Join ΒΆ added in v0.2.793

func Join(components ...Component) Component

Join returns a single `templ.Component` that will render provided components in order. If any of the components return an error the Join component will immediately return with the error.

func Raw ΒΆ added in v0.2.501

func Raw[T ~string](html T, errs ...error) Component

Raw renders the input HTML to the output without applying HTML escaping.

Use of this component presents a security risk - the HTML should come from a trusted source, because it will be included as-is in the output.

type ComponentCSSClass ΒΆ added in v0.0.113

type ComponentCSSClass struct {
	// ID of the class, will be autogenerated.
	ID string
	// Definition of the CSS.
	Class SafeCSS
}

ComponentCSSClass is a templ.CSS

func (ComponentCSSClass) ClassName ΒΆ added in v0.0.113

func (css ComponentCSSClass) ClassName() string

ClassName of the CSS class.

type ComponentFunc ΒΆ

type ComponentFunc func(ctx context.Context, w io.Writer) error

ComponentFunc converts a function that matches the Component interface's Render method into a Component.

func (ComponentFunc) Render ΒΆ

func (cf ComponentFunc) Render(ctx context.Context, w io.Writer) error

Render the template.

type ComponentHandler ΒΆ added in v0.0.139

type ComponentHandler struct {
	Component      Component
	Status         int
	ContentType    string
	ErrorHandler   func(r *http.Request, err error) http.Handler
	StreamResponse bool
	FragmentIDs    []any
}

ComponentHandler is a http.Handler that renders components.

func Handler ΒΆ added in v0.0.139

func Handler(c Component, options ...func(*ComponentHandler)) *ComponentHandler

Handler creates a http.Handler that renders the template.

func (ComponentHandler) ServeHTTP ΒΆ added in v0.0.139

func (ch ComponentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface.

func (*ComponentHandler) ServeHTTPBuffered ΒΆ added in v0.2.731

func (ch *ComponentHandler) ServeHTTPBuffered(w http.ResponseWriter, r *http.Request)

func (*ComponentHandler) ServeHTTPBufferedComplete ΒΆ added in v0.3.920

func (ch *ComponentHandler) ServeHTTPBufferedComplete(w http.ResponseWriter, r *http.Request)

func (*ComponentHandler) ServeHTTPBufferedFragment ΒΆ added in v0.3.920

func (ch *ComponentHandler) ServeHTTPBufferedFragment(w http.ResponseWriter, r *http.Request)

func (*ComponentHandler) ServeHTTPStreamed ΒΆ added in v0.2.731

func (ch *ComponentHandler) ServeHTTPStreamed(w http.ResponseWriter, r *http.Request)

type ComponentScript ΒΆ added in v0.0.139

type ComponentScript struct {
	// Name of the script, e.g. print.
	Name string
	// Function to render.
	Function string
	// Call of the function in JavaScript syntax, including parameters, and
	// ensures parameters are HTML escaped; useful for injecting into HTML
	// attributes like onclick, onhover, etc.
	//
	// Given:
	//    functionName("some string",12345)
	// It would render:
	//    __templ_functionName_sha(&#34;some string&#34;,12345))
	//
	// This is can be injected into HTML attributes:
	//    <button onClick="__templ_functionName_sha(&#34;some string&#34;,12345))">Click Me</button>
	Call string
	// Call of the function in JavaScript syntax, including parameters. It
	// does not HTML escape parameters; useful for directly calling in script
	// elements.
	//
	// Given:
	//    functionName("some string",12345)
	// It would render:
	//    __templ_functionName_sha("some string",12345))
	//
	// This is can be used to call the function inside a script tag:
	//    <script>__templ_functionName_sha("some string",12345))</script>
	CallInline string
}

ComponentScript is a templ Script template.

func JSFuncCall ΒΆ added in v0.3.833

func JSFuncCall[T ~string](functionName T, args ...any) ComponentScript

JSFuncCall calls a JavaScript function with the given arguments.

It can be used in event handlers, e.g. onclick, onhover, etc. or directly in HTML.

func JSUnsafeFuncCall ΒΆ added in v0.3.833

func JSUnsafeFuncCall[T ~string](js T) ComponentScript

JSUnsafeFuncCall calls arbitrary JavaScript in the js parameter.

Use of this function presents a security risk - the JavaScript must come from a trusted source, because it will be included as-is in the output.

func (ComponentScript) Render ΒΆ added in v0.2.476

func (c ComponentScript) Render(ctx context.Context, w io.Writer) error

type ConstantCSSClass ΒΆ added in v0.0.113

type ConstantCSSClass string

ConstantCSSClass is a string constant of a CSS class name. Deprecated: use a string instead.

func (ConstantCSSClass) ClassName ΒΆ added in v0.0.113

func (css ConstantCSSClass) ClassName() string

ClassName of the CSS class.

type Error ΒΆ added in v0.2.501

type Error struct {
	Err error
	// FileName of the template file.
	FileName string
	// Line index of the error.
	Line int
	// Col index of the error.
	Col int
}

Error returned during template rendering.

func (Error) Error ΒΆ added in v0.2.501

func (e Error) Error() string

func (Error) Unwrap ΒΆ added in v0.2.501

func (e Error) Unwrap() error

type FlushComponent ΒΆ added in v0.2.731

type FlushComponent struct {
}

func Flush ΒΆ added in v0.2.731

func Flush() FlushComponent

Flush flushes the output buffer after all its child components have been rendered.

func (FlushComponent) Render ΒΆ added in v0.2.731

func (f FlushComponent) Render(ctx context.Context, w io.Writer) (err error)

type FragmentContext ΒΆ added in v0.3.920

type FragmentContext struct {
	W      io.Writer
	IDs    []any
	Active bool
}

FragmentContext is used to control rendering of fragments within a template.

type JSExpression ΒΆ added in v0.2.771

type JSExpression string

JSExpression represents a JavaScript expression intended for use as an argument for script templates. The string value of JSExpression will be inserted directly as JavaScript code in function call arguments.

type JSONScriptElement ΒΆ added in v0.2.707

type JSONScriptElement struct {
	// ID of the element in the DOM.
	ID string
	// Type of the script element, defaults to "application/json".
	Type string
	// Data that will be encoded as JSON.
	Data any
	// Nonce is a function that returns a CSP nonce.
	// Defaults to CSPNonceFromContext.
	// See https://content-security-policy.com/nonce for more information.
	Nonce func(ctx context.Context) string
}

func JSONScript ΒΆ added in v0.2.707

func JSONScript(id string, data any) JSONScriptElement

JSONScript renders a JSON object inside a script element. e.g. <script type="application/json">{"foo":"bar"}</script>

func (JSONScriptElement) Render ΒΆ added in v0.2.707

func (j JSONScriptElement) Render(ctx context.Context, w io.Writer) (err error)

func (JSONScriptElement) WithNonceFrom ΒΆ added in v0.2.707

func (j JSONScriptElement) WithNonceFrom(f func(context.Context) string) JSONScriptElement

WithNonceFrom sets the value of the nonce attribute of the script element to the value returned by the given function.

func (JSONScriptElement) WithNonceFromString ΒΆ added in v0.2.707

func (j JSONScriptElement) WithNonceFromString(nonce string) JSONScriptElement

WithNonceFromString sets the value of the nonce attribute of the script element to the given string.

func (JSONScriptElement) WithType ΒΆ added in v0.2.731

WithType sets the value of the type attribute of the script element.

type KeyValue ΒΆ added in v0.2.282

type KeyValue[TKey comparable, TValue any] struct {
	Key   TKey   `json:"name"`
	Value TValue `json:"value"`
}

KeyValue is a key and value pair.

func KV ΒΆ added in v0.2.282

func KV[TKey comparable, TValue any](key TKey, value TValue) KeyValue[TKey, TValue]

KV creates a new key/value pair from the input key and value.

type OnceHandle ΒΆ added in v0.2.707

type OnceHandle struct {
	// contains filtered or unexported fields
}

OnceHandle is used to ensure that the children of its `Once` method are are only rendered once per context.

func NewOnceHandle ΒΆ added in v0.2.707

func NewOnceHandle(opts ...OnceOpt) *OnceHandle

NewOnceHandle creates a OnceHandle used to ensure that the children of its `Once` method are only rendered once per context.

func (*OnceHandle) Once ΒΆ added in v0.2.707

func (o *OnceHandle) Once() Component

Once returns a component that renders its children once per context.

type OnceOpt ΒΆ added in v0.2.707

type OnceOpt func(*OnceHandle)

func WithComponent ΒΆ added in v0.2.707

func WithComponent(c Component) OnceOpt

WithOnceComponent sets the component to be rendered once per context. This can be used instead of setting the children of the `Once` method, for example, if creating a code component outside of a templ HTML template.

type OrderedAttributes ΒΆ added in v0.3.865

type OrderedAttributes []KeyValue[string, any]

OrderedAttributes stores attributes in order of insertion.

func (OrderedAttributes) Items ΒΆ added in v0.3.865

func (a OrderedAttributes) Items() []KeyValue[string, any]

type SafeCSS ΒΆ added in v0.0.113

type SafeCSS string

SafeCSS is CSS that has been sanitized.

func SanitizeCSS ΒΆ added in v0.0.113

func SanitizeCSS[T ~string](property string, value T) SafeCSS

SanitizeCSS sanitizes CSS properties to ensure that they are safe.

type SafeCSSProperty ΒΆ added in v0.2.619

type SafeCSSProperty string

type SafeURL ΒΆ added in v0.0.113

type SafeURL string

SafeURL is a URL that has been sanitized.

func JoinURLErrs ΒΆ added in v0.3.898

func JoinURLErrs[T ~string](s T, errs ...error) (SafeURL, error)

JoinURLErrs joins an optional list of errors and returns a sanitized SafeURL.

func URL ΒΆ added in v0.0.113

func URL(s string) SafeURL

URL sanitizes the input string s and returns a SafeURL.

Directories ΒΆ

Path Synopsis
benchmarks
This package is inspired by the GOEXPERIMENT approach of allowing feature flags for experimenting with breaking changes.
This package is inspired by the GOEXPERIMENT approach of allowing feature flags for experimenting with breaking changes.
cmd
templ command
examples
hello-world-ssr command
blog module
counter module
counter-basic module
crud module
typescript module
internal
lsp
jsonrpc2
Package jsonrpc2 is an implementation of the JSON-RPC 2 specification for Go.
Package jsonrpc2 is an implementation of the JSON-RPC 2 specification for Go.
protocol
Package protocol implements Language Server Protocol specification in Go.
Package protocol implements Language Server Protocol specification in Go.
uri
xcontext
Package xcontext is a package to offer the extra functionality we need from contexts that is not available from the standard context package.
Package xcontext is a package to offer the extra functionality we need from contexts that is not available from the standard context package.
parser
v2
fuzzing module