templ – github.com/a-h/templ Index | Files | Directories

package templ

import "github.com/a-h/templ"

Index

Constants

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

FailedSanitizationURL is returned if a URL fails sanitization checks.

Variables

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

func Bool(value bool) bool

Bool attribute value.

func CSSID

func CSSID(name string, css string) string

CSSID calculates an ID.

func ClearChildren

func ClearChildren(ctx context.Context) context.Context

func EscapeString

func EscapeString(s string) string

EscapeString escapes HTML text within templates.

func GetBuffer

func GetBuffer() *bytes.Buffer

func GetNonce

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

func InitializeContext(ctx context.Context) context.Context

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

func JSONString

func JSONString(v any) (string, error)

JSONString returns a JSON encoded string of v.

func JoinStringErrs

func JoinStringErrs(s string, errs ...error) (string, error)

JoinStringErrs joins an optional list of errors.

func ReleaseBuffer

func ReleaseBuffer(b *bytes.Buffer)

func RenderAttributes

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

func RenderCSSItems

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 RenderScriptItems

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

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

SafeScript encodes unknown parameters for safety for inside HTML attributes.

func SafeScriptInline

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

SafeScript encodes unknown parameters for safety for inline scripts.

func ToGoHTML

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

func Version() string

func WithChildren

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

func WithContentType

func WithContentType(contentType string) func(*ComponentHandler)

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

func WithErrorHandler

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

WithErrorHandler sets the error handler used if rendering fails.

func WithNonce

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

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

func WithStatus

func WithStatus(status int) func(*ComponentHandler)

WithStatus sets the HTTP status code returned by the ComponentHandler.

func WithStreaming

func WithStreaming() func(*ComponentHandler)

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

func WriteWatchModeString

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 Attributes

type Attributes map[string]any

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

type CSSClass

type CSSClass interface {
	ClassName() string
}

CSSClass provides a class name.

func Class

func Class(name string) CSSClass

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

func SafeClass

func SafeClass(name string) CSSClass

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

type CSSClasses

type CSSClasses []any

CSSClasses is a slice of CSS classes.

func Classes

func Classes(classes ...any) CSSClasses

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

func (CSSClasses) String

func (classes CSSClasses) String() string

String returns the names of all CSS classes.

type CSSHandler

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

CSSHandler is a HTTP handler that serves CSS.

func NewCSSHandler

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

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

type CSSMiddleware

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

CSSMiddleware renders a global stylesheet.

func NewCSSMiddleware

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

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 FromGoHTML

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

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

func GetChildren

func GetChildren(ctx context.Context) Component

GetChildren from the context.

func Join

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

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

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

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

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

ComponentHandler is a http.Handler that renders components.

func Handler

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

Handler creates a http.Handler that renders the template.

func (ComponentHandler) ServeHTTP

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

ServeHTTP implements the http.Handler interface.

func (*ComponentHandler) ServeHTTPBuffered

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

func (*ComponentHandler) ServeHTTPStreamed

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

type ComponentScript

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

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

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

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

type ConstantCSSClass

type ConstantCSSClass string

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

func (ConstantCSSClass) ClassName

func (css ConstantCSSClass) ClassName() string

ClassName of the CSS class.

type Error

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

func (e Error) Error() string

func (Error) Unwrap

func (e Error) Unwrap() error

type FlushComponent

type FlushComponent struct {
}

func Flush

func Flush() FlushComponent

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

func (FlushComponent) Render

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

type JSExpression

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

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

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

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

func (JSONScriptElement) WithNonceFrom

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

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

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

type KeyValue

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

KeyValue is a key and value pair.

func KV

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

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

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

func (o *OnceHandle) Once() Component

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

type OnceOpt

type OnceOpt func(*OnceHandle)

func WithComponent

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 SafeCSS

type SafeCSS string

SafeCSS is CSS that has been sanitized.

func SanitizeCSS

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

SanitizeCSS sanitizes CSS properties to ensure that they are safe.

type SafeCSSProperty

type SafeCSSProperty string

type SafeURL

type SafeURL string

SafeURL is a URL that has been sanitized.

func URL

func URL(s string) SafeURL

URL sanitizes the input string s and returns a SafeURL.

Source Files

flush.go handler.go join.go js.go jsonscript.go jsonstring.go once.go runtime.go scripttemplate.go url.go version.go watchmode.go

Directories

PathSynopsis
benchmarks
benchmarks/templ
cfgThis package is inspired by the GOEXPERIMENT approach of allowing feature flags for experimenting with breaking changes.
cmd
cmd/templ
cmd/templ/fmtcmd
cmd/templ/generatecmd
cmd/templ/generatecmd/modcheck
cmd/templ/generatecmd/proxy
cmd/templ/generatecmd/run
cmd/templ/generatecmd/run/testprogram
cmd/templ/generatecmd/sse
cmd/templ/generatecmd/symlink
cmd/templ/generatecmd/test-eventhandler
cmd/templ/generatecmd/testwatch
cmd/templ/generatecmd/watcher
cmd/templ/imports
cmd/templ/infocmd
cmd/templ/lspcmd
cmd/templ/lspcmd/httpdebug
cmd/templ/lspcmd/lspdiff
cmd/templ/lspcmd/pls
cmd/templ/lspcmd/proxy
cmd/templ/processor
cmd/templ/sloghandler
cmd/templ/testproject
cmd/templ/visualize
examples
examples/content-security-policy
examples/hello-world-ssr
examples/hello-world-static
examples/syntax-and-usage
examples/syntax-and-usage/components
generator
generator/htmldiff
generator/test-a-href
generator/test-attribute-errors
generator/test-attribute-escaping
generator/test-call
generator/test-cancelled-context
generator/test-complex-attributes
generator/test-constant-attribute-escaping
generator/test-context
generator/test-css-expression
generator/test-css-middleware
generator/test-css-usage
generator/test-doctype
generator/test-doctype-html4
generator/test-element-attributes
generator/test-elseif
generator/test-for
generator/test-form-action
generator/test-go-comments
generator/test-go-template-in-templ
generator/test-html
generator/test-html-comment
generator/test-if
generator/test-ifelse
generator/test-import
generator/test-js-unsafe-usage
generator/test-js-usage
generator/test-method
generator/test-once
generator/test-only-scripts
generator/test-raw-elements
generator/test-script-expressions
generator/test-script-inline
generator/test-script-usage
generator/test-script-usage-nonce
generator/test-spread-attributes
generator/test-string
generator/test-string-errors
generator/test-style-attribute
generator/test-switch
generator/test-switchdefault
generator/test-templ-element
generator/test-templ-in-go-template
generator/test-text
generator/test-text-whitespace
generator/test-void
generator/test-whitespace-around-go-keywords
internal
lsp
lsp/jsonrpc2Package jsonrpc2 is an implementation of the JSON-RPC 2 specification for Go.
lsp/protocolPackage protocol implements Language Server Protocol specification in Go.
lsp/uri
lsp/xcontextPackage xcontext is a package to offer the extra functionality we need from contexts that is not available from the standard context package.
parser
parser/v2
parser/v2/goexpression
runtime
safehtml
storybook
turbo
Version
v0.3.857 (latest)
Published
Mar 25, 2025
Platform
linux/amd64
Imports
23 packages
Last checked
1 week ago

Tools for package owners.