render

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2025 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// LayoutsDir is the directory for layout templates
	LayoutsDir = "layouts"

	// PartialsDir is the directory for partial templates
	PartialsDir = "partials"

	// ViewsDir is the directory for view templates
	ViewsDir = "views"

	// SystemDir is the directory for system templates
	SystemDir = "system"

	// DefaultBaseLayout is the default base layout template
	DefaultBaseLayout = "base"

	// NonceContextKey is the key used for the a front-end nonce
	NonceContextKey = "hyperview_nonce"
)
View Source
const (
	// ErrTempNotFound is returned when a template is not found.
	ErrTempNotFound = hyperViewError("template not found")

	// ErrTempParse is returned when a template cannot be parsed.
	ErrTempParse = hyperViewError("template parse error")

	// ErrTempRender is returned when a template cannot be rendered.
	ErrTempRender = hyperViewError("template render error")
)
View Source
const (
	PageDataPageKey   = "Page"
	PageDataErrorKey  = "Error"
	PageDataErrorsKey = "Errors"
)

Variables

This section is empty.

Functions

func MergeIntoFuncMap added in v0.0.32

func MergeIntoFuncMap(dst template.FuncMap, maps ...template.FuncMap)

MergeIntoFuncMap merges the provided function maps into the provided function map.

Types

type LinkData added in v0.0.30

type LinkData struct {
	Path   string
	Title  string
	Active bool
}

type PageData added in v0.0.24

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

PageData is the struct that all view models must implement. It provides common data for all templates and represents the data that is passed to the template.

This is a short-lived object that is used to work with data passed to the template. It is not thread-safe.

PageData should not be used directly. Instead, use the NewPageData function to create an instance of PageData that contains the data you want to pass to the template.

Example: NewPageData(request, map[string]any{"title": "Hello World"})

The environment variables are generally added via conf/config, but if you're not using that package, you can set them manually.

func NewPageData added in v0.0.24

func NewPageData(pageData map[string]any) *PageData

NewPageData creates a new PageData instance. If you are using this outside the normal HyperView rendering process, be sure to set the request manually via PageData.SetRequest as the request is deliberately set later in the normal rendering flow.

func (v *PageData) ActiveLink(path, title string) LinkData

ActiveLink returns a LinkData struct with the provided path and title.

func (v *PageData) ActivePrefixLink(path, title, prefix string) LinkData

ActivePrefixLink returns a LinkData struct with the provided path and title, where the active state is determined by the prefix.

func (v *PageData) ActiveSuffixLink(path, title, suffix string) LinkData

ActiveSuffixLink returns a LinkData struct with the provided path and title, where the active state is determined by the suffix.

func (*PageData) BaseURL added in v0.0.24

func (v *PageData) BaseURL() string

BaseURL returns the base URL of the request.

func (*PageData) Context added in v0.0.24

func (v *PageData) Context() context.Context

Context returns the context of the request.

func (*PageData) CurrentYear added in v0.0.24

func (v *PageData) CurrentYear() int

CurrentYear returns the current year.

func (*PageData) Data added in v0.0.24

func (v *PageData) Data() map[string]any

Data returns the data map that will be passed to the template. It will include the PageData instance itself as the "Page" key.

func (*PageData) Error added in v0.0.24

func (v *PageData) Error() string

Error returns the error message from the view data model.

func (*PageData) ErrorFor added in v0.0.24

func (v *PageData) ErrorFor(field string) string

ErrorFor returns the error message for the specified field from the view data model.

func (*PageData) Errors added in v0.0.24

func (v *PageData) Errors() map[string]string

Errors returns a map of field errors from the view data model.

func (*PageData) Get added in v0.0.24

func (v *PageData) Get(key string) any

Get returns the value of the specified key from the view data model.

func (*PageData) GetString added in v0.0.24

func (v *PageData) GetString(key string) string

GetString returns the value of the specified key from the view data model as a string.

func (*PageData) HasError added in v0.0.24

func (v *PageData) HasError() bool

HasError returns true if the view data model contains an error message.

func (*PageData) HasErrorFor added in v0.0.24

func (v *PageData) HasErrorFor(field string) bool

HasErrorFor returns true if the view data model contains an error message for the specified field.

func (*PageData) HasErrors added in v0.0.24

func (v *PageData) HasErrors() bool

HasErrors returns true if the view data model contains field errors.

func (*PageData) HxNonce added in v0.0.24

func (v *PageData) HxNonce() string

HxNonce returns the HTMX nonce value from the request context, if available. This adds the inlineScriptNonce key to a JSON object with the nonce value and can be used in an HTMX meta tag.

func (*PageData) IsBoostedRequest added in v0.0.24

func (v *PageData) IsBoostedRequest() bool

IsBoostedRequest returns true if the request is a boosted request.

func (*PageData) IsHtmxRequest added in v0.0.24

func (v *PageData) IsHtmxRequest() bool

IsHtmxRequest returns true if the request is an HTMX request, but not a boosted request.

func (*PageData) Merge added in v0.0.24

func (v *PageData) Merge(data map[string]any)

Merge adds a map of data to the existing view data model.

func (*PageData) Nonce added in v0.0.24

func (v *PageData) Nonce() string

Nonce returns the nonce value from the request context, if available.

func (*PageData) RequestMethod added in v0.0.24

func (v *PageData) RequestMethod() string

RequestMethod returns the method of the request.

func (*PageData) RequestPath added in v0.0.24

func (v *PageData) RequestPath() string

RequestPath returns the path of the request.

func (*PageData) Set added in v0.0.24

func (v *PageData) Set(key string, value any)

Set adds a single key-value pair to the existing view data model.

func (*PageData) SetRequest added in v0.0.24

func (v *PageData) SetRequest(r *http.Request)

SetRequest sets the request for the PageData instance.

func (*PageData) SetTitle added in v0.0.24

func (v *PageData) SetTitle(title string)

SetTitle sets the title of the page.

func (*PageData) Title added in v0.0.24

func (v *PageData) Title() string

Title returns the title of the page.

type Response

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

Response represents a view response to an HTTP request It uses a fluent interface to allow for chaining of methods, so that methods can be called in any order.

func NewResponse

func NewResponse(tm *TemplateManager, manager *flash.Manager) *Response

NewResponse creates a new Response struct with the provided template manager.

func (*Response) CacheControl

func (resp *Response) CacheControl(cacheControl string) *Response

CacheControl sets the Cache-Control header to the given value.

func (*Response) Data

func (resp *Response) Data(key string, value any) *Response

Data adds a single data item to the view data model. It returns the modified Response pointer.

func (*Response) Description added in v0.0.24

func (resp *Response) Description(description string) *Response

Description sets the page description

func (*Response) ETag

func (resp *Response) ETag(etag string) *Response

ETag sets the ETag header to the given value.

func (*Response) GetHTTPHeader added in v0.0.24

func (resp *Response) GetHTTPHeader() http.Header

GetHTTPHeader returns a http.Header for the headers map

func (*Response) GetHeaders added in v0.0.24

func (resp *Response) GetHeaders() map[string]string

GetHeaders returns the headers map as a combination map of both triggers and headers

func (*Response) GetPageDescription added in v0.0.24

func (resp *Response) GetPageDescription() string

GetPageDescription returns the page description

func (*Response) GetPageTitle added in v0.0.24

func (resp *Response) GetPageTitle() string

GetPageTitle returns the page title

func (*Response) GetStatusCode added in v0.0.24

func (resp *Response) GetStatusCode() int

GetStatusCode returns the status code.

func (*Response) GetTemplateLayout added in v0.0.24

func (resp *Response) GetTemplateLayout() string

GetTemplateLayout returns the template layout

func (*Response) GetTemplatePath added in v0.0.24

func (resp *Response) GetTemplatePath() string

GetTemplatePath returns the path used in templates, if any

func (*Response) Header

func (resp *Response) Header(key, value string) *Response

Header adds/sets a header

func (*Response) HxLayout

func (resp *Response) HxLayout(r *http.Request, hxLayout, layout string) *Response

HxLayout sets the layout for HTMX requests if the request is an HTMX request, otherwise it uses the default layout.

Parameters:

  • request is used to determine if the request is an HTMX request.
  • hxLayout is the layout to use for HTMX requests.
  • layout is the default layout to use if the request is not an HTMX request.

func (*Response) HxLocation

func (resp *Response) HxLocation(path string, opt ...location.Option) *Response

HxLocation sets the HX-Location header, which instructs the browser to navigate to the given path without reloading the page.

For simple navigations, use a path and no HxLocation options. For more complex navigations, use the HxLocation options to fine-tune the navigation.

Sets the HX-Location header with the given path.

For more information, see: https://htmx.org/headers/hx-location

func (*Response) HxNoPushURL

func (resp *Response) HxNoPushURL() *Response

HxNoPushURL prevents the browser from updating the history stack by setting the HX-Push-Url header to "false".

For more information, see: https://htmx.org/headers/hx-no-push-url

func (*Response) HxNoRefresh

func (resp *Response) HxNoRefresh() *Response

HxNoRefresh prevents the browser from reloading the page by setting the HX-Refresh header to "false".

For more information, see: https://htmx.org/reference/#response_headers

func (*Response) HxNoReplaceURL

func (resp *Response) HxNoReplaceURL() *Response

HxNoReplaceURL prevents the browser from updating the history stack by setting the HX-Replace-Url header to "false".

For more information, see: https://htmx.org/headers/hx-replace-url

func (*Response) HxPushURL

func (resp *Response) HxPushURL(path string) *Response

HxPushURL sets the HX-Push-Url header, which instructs the browser to navigate to the given path without reloading the page.

To prevent the browser from updating the page, set the HX-Push-Url header to an empty string or "false".

For more information, see: https://htmx.org/headers/hx-push-url

func (*Response) HxRedirect

func (resp *Response) HxRedirect(path string) *Response

HxRedirect sets the HX-Redirect header, which instructs the browser to navigate to the given path (this will reload the page).

For more information, see: https://htmx.org/reference/#response_headers

func (*Response) HxRefresh

func (resp *Response) HxRefresh() *Response

HxRefresh sets the HX-Refresh header, which instructs the browser to reload the page.

For more information, see: https://htmx.org/reference/#response_headers

func (*Response) HxReplaceURL

func (resp *Response) HxReplaceURL(path string) *Response

HxReplaceURL sets the HX-Replace-Url header, which instructs the browser to replace the history stack with the given path.

For more information, see: https://htmx.org/headers/hx-replace-url

func (*Response) HxReselect

func (resp *Response) HxReselect(reselect string) *Response

HxReselect sets the HX-ReSelect header, which instructs HTMX to update which part of the response is selected.

For more information, see: https://htmx.org/reference/#response_headers and https://htmx.org/attributes/hx-select

func (*Response) HxReswap

func (resp *Response) HxReswap(swap *swap.Style) *Response

HxReswap sets the HX-Reswap header, which instructs HTMX to change the swap behavior of the target element.

For more information, see: https://htmx.org/attributes/hx-swap

func (*Response) HxRetarget

func (resp *Response) HxRetarget(target string) *Response

HxRetarget sets the HX-Retarget header, which instructs HTMX to update the target element.

For more information, see: https://htmx.org/reference/#response_headers

func (*Response) HxTrigger

func (resp *Response) HxTrigger(event string, value any) *Response

HxTrigger sets a HX-Trigger header

For more information, see: https://htmx.org/headers/hx-trigger/

func (*Response) HxTriggerAfterSettle

func (resp *Response) HxTriggerAfterSettle(event string, value any) *Response

HxTriggerAfterSettle sets a HX-Trigger-After-Settle header

For more information, see: https://htmx.org/headers/hx-trigger/

func (*Response) HxTriggerAfterSwap

func (resp *Response) HxTriggerAfterSwap(event string, value any) *Response

HxTriggerAfterSwap sets a HX-Trigger-After-Swap header

For more information, see: https://htmx.org/headers/hx-trigger/

func (*Response) LastModified

func (resp *Response) LastModified(lastModified string) *Response

LastModified sets the Last-Modified header to the given value.

func (*Response) Layout

func (resp *Response) Layout(layout string) *Response

Layout sets the template layout. It updates the layout value in the Response struct. Then it returns the updated Response struct itself for method chaining.

func (*Response) MergeData added in v0.0.24

func (resp *Response) MergeData(data map[string]any) *Response

MergeData adds data to the view data model. It returns the modified Response pointer.

func (*Response) NoCacheStrict

func (resp *Response) NoCacheStrict() *Response

NoCacheStrict sets the Cache-Control header to "no-cache, no-store, must-revalidate".

func (*Response) PageData added in v0.0.24

func (resp *Response) PageData(r *http.Request) *PageData

PageData returns the page data model. The request is set here to ensure the request is available in the template and that it is not overwritten until later in the process.

func (*Response) Path

func (resp *Response) Path(path string) *Response

Path sets the template path

func (*Response) Redirect

func (resp *Response) Redirect(w http.ResponseWriter, r *http.Request, url string)

Redirect sends a redirect response to the client

func (*Response) RedirectWithHTMX

func (resp *Response) RedirectWithHTMX(w http.ResponseWriter, url string)

RedirectWithHTMX sends an HX-Redirect header to the client

func (*Response) Render

func (resp *Response) Render(w http.ResponseWriter, r *http.Request)

Render renders the response using the template manager Example: resp.StatusOK().Render(w, r)

func (*Response) RenderForbidden

func (resp *Response) RenderForbidden(w http.ResponseWriter, r *http.Request)

RenderForbidden renders the 403 Forbidden page

func (*Response) RenderMaintenance

func (resp *Response) RenderMaintenance(w http.ResponseWriter, r *http.Request)

RenderMaintenance renders the 503 Service Unavailable page

func (*Response) RenderMethodNotAllowed

func (resp *Response) RenderMethodNotAllowed(w http.ResponseWriter, r *http.Request)

RenderMethodNotAllowed renders the 405 Method Not Allowed page

func (*Response) RenderNotFound

func (resp *Response) RenderNotFound(w http.ResponseWriter, r *http.Request)

RenderNotFound renders the 404 Not Found page

func (*Response) RenderSystemError

func (resp *Response) RenderSystemError(w http.ResponseWriter, r *http.Request, err error)

RenderSystemError renders the 500 Internal Server Error page

func (*Response) RenderUnauthorized

func (resp *Response) RenderUnauthorized(w http.ResponseWriter, r *http.Request)

RenderUnauthorized renders the 401 Unauthorized page

func (*Response) Status

func (resp *Response) Status(status int) *Response

Status sets the status code.

func (*Response) StatusAccepted

func (resp *Response) StatusAccepted() *Response

StatusAccepted sets the status code to Accepted (202) and returns the Response object.

func (*Response) StatusCreated

func (resp *Response) StatusCreated() *Response

StatusCreated sets the status code to Created (201)

func (*Response) StatusError

func (resp *Response) StatusError() *Response

StatusError sets the status code to InternalServerError (500)

func (*Response) StatusForbidden

func (resp *Response) StatusForbidden() *Response

StatusForbidden sets the status code to Forbidden (403) and returns the Response object.

func (*Response) StatusNoContent

func (resp *Response) StatusNoContent() *Response

StatusNoContent sets the status code to NoContent (204). It returns the Response object for method chaining.

func (*Response) StatusNotFound

func (resp *Response) StatusNotFound() *Response

StatusNotFound sets the status code to NotFound (404)

func (*Response) StatusOK

func (resp *Response) StatusOK() *Response

StatusOK sets the status code to OK (200)

func (*Response) StatusStopPolling

func (resp *Response) StatusStopPolling() *Response

StatusStopPolling sets the status code to 286 and returns the Response object. This is useful when working HTMX and polling. Responding with a status of 286 will tell HTMX to stop polling. SEE: https://htmx.org/docs/#polling

func (*Response) StatusUnauthorized

func (resp *Response) StatusUnauthorized() *Response

StatusUnauthorized sets the status code to Unauthorized (401)

func (*Response) StatusUnavailable

func (resp *Response) StatusUnavailable() *Response

StatusUnavailable sets the status code to ServiceUnavailable (503)

func (*Response) StatusUnprocessable

func (resp *Response) StatusUnprocessable() *Response

StatusUnprocessable sets the status code to UnprocessableEntity (422)

func (*Response) Title

func (resp *Response) Title(title string) *Response

Title sets the page title

func (*Response) WithData added in v0.0.24

func (resp *Response) WithData(data map[string]any) *Response

WithData creates a new view data model with the provided data map and returns the modified Response pointer. This will overwrite any existing view data model. If you want to add data to an existing view data model, create a new view data model externally using the NewPageData function and pass it to the WithPageData function instead.

func (*Response) WithError added in v0.0.24

func (resp *Response) WithError(msg string) *Response

WithError adds an error message to the view data model. This will also set the status code to 422 (Unprocessable Entity)).

func (*Response) WithErrors added in v0.0.24

func (resp *Response) WithErrors(msg string, fieldErrors map[string]string) *Response

WithErrors adds an error message and a map of field errors to the view data model. This will also set the status code to 422 (Unprocessable Entity)). If that is not the desired status code, you should reset it using the Status() function or one of the Status* shortcut functions.

func (*Response) WithPageData added in v0.0.24

func (resp *Response) WithPageData(data *PageData) *Response

WithPageData resets the view data model with an existing model. It returns the modified Response pointer. The view data model contains data that will be passed to the view template for rendering.

Alternatively, you can add the data map and create a new view data model automatically using the WithData function.

Important: if you are creating the view data model externally and need to use it before render is called, you should probably set the request via PageData.SetRequest, as the request is deliberately set later in the rendering process in most cases.

type Sources

type Sources map[string]fs.FS

type TemplateManager

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

TemplateManager is a template adapter for the HyperView framework that uses the Go html/template package.

func NewTemplateManager

func NewTemplateManager(sources Sources, opts TemplateManagerOptions) (*TemplateManager, error)

NewTemplateManager creates a new TemplateManager. Accepts a map of file systems, a logger, and options for configuration. For sources, if the string key is empty or "-", it will be treated as the default file system. Otherwise, the key is used as the file system ID. e.g., "foo:bar" for a template named "bar" in the "foo" file system.

func (*TemplateManager) Initialize added in v0.0.24

func (tm *TemplateManager) Initialize() error

Initialize sets up the template manager and preloads critical templates

func (*TemplateManager) NewResponse

func (tm *TemplateManager) NewResponse(manager *flash.Manager) *Response

NewResponse creates a new Response instance with the TemplateManager.

func (*TemplateManager) SetErrorTemplate added in v0.0.25

func (tm *TemplateManager) SetErrorTemplate(layout string)

SetErrorTemplate sets the template to use for rendering system errors.

type TemplateManagerOptions

type TemplateManagerOptions struct {
	// BaseLayout is the default layout to use for rendering templates. Default is "base".
	BaseLayout string

	// SystemLayout is the layout to use for system pages (e.g. 404, 500). Default is "base".
	SystemLayout string

	// Extension is the file extension for the templates. Default is ".html".
	Extension string

	// Funcs is a map of functions to add to default set of template functions made available. See the `templates/funcmap` package for a list of default functions.
	Funcs template.FuncMap

	// Logger is the logger to use for logging errors. Default is nil.
	Logger *slog.Logger
}

TemplateManagerOptions are the options for the TemplateManager.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL