render

package
v0.0.11 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2024 License: Apache-2.0 Imports: 24 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")
)

Variables

This section is empty.

Functions

func DefaultFuncMap

func DefaultFuncMap() template.FuncMap

func MergeFuncMaps

func MergeFuncMaps(funcMap template.FuncMap) template.FuncMap

MergeFuncMaps merges the provided function map with the default function map. If there are any conflicts, the provided function map will take precedence.

Types

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) *Response

func (*Response) AddData

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

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

func (*Response) AddDataItem

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

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

func (*Response) CacheControl

func (resp *Response) CacheControl(cacheControl string)

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

func (*Response) Data

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

Data 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 NewResponseData function and pass it to the ResetData function instead.

func (*Response) ETag

func (resp *Response) ETag(etag string)

ETag sets the ETag header to the given value.

func (*Response) Errors

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

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

func (*Response) HTTPHeader

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

HTTPHeader returns a http.Header for the headers map

func (*Response) Header

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

Header adds/sets a header

func (*Response) Headers

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

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

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)

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) NoCacheStrict

func (resp *Response) NoCacheStrict()

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

func (*Response) PageTitle

func (resp *Response) PageTitle() string

PageTitle returns the page title

func (*Response) Path

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

Path sets the template path

func (*Response) Redirect

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

Redirect sends a redirect response to the client

func (*Response) RedirectOLD

func (resp *Response) RedirectOLD(w http.ResponseWriter, r *http.Request, url string, status int)

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) ResetData

func (resp *Response) ResetData(data *ResponseData) *Response

ResetData 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 Data 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 Data.SetRequest, as the request is deliberately set later in the rendering process in most cases.

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) StatusCode

func (resp *Response) StatusCode() int

StatusCode returns the status code.

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) TemplateLayout

func (resp *Response) TemplateLayout() string

TemplateLayout returns the template layout

func (*Response) TemplatePath

func (resp *Response) TemplatePath() string

TemplatePath returns the path used in templates, if any

func (*Response) Title

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

Title sets the page title

func (*Response) ViewData

func (resp *Response) ViewData(r *http.Request) *ResponseData

ViewData returns the view 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.

type ResponseData

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

ResponseData 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.

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

Example: NewResponseData(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 NewResponseData

func NewResponseData(pageData map[string]any) *ResponseData

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

func (*ResponseData) AddData

func (v *ResponseData) AddData(data map[string]any)

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

func (*ResponseData) AddDataItem

func (v *ResponseData) AddDataItem(key string, value any)

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

func (*ResponseData) AddErrors

func (v *ResponseData) AddErrors(msg string, fieldErrors map[string]string)

AddErrors adds an error message and a map of field errors to the view data model.

func (*ResponseData) BaseURL

func (v *ResponseData) BaseURL() string

BaseURL returns the base URL of the request.

func (*ResponseData) Context

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

Context returns the context of the request.

func (*ResponseData) CurrentYear

func (v *ResponseData) CurrentYear() int

CurrentYear returns the current year.

func (*ResponseData) Data

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

Data returns the data map that will be passed to the template.

func (*ResponseData) Error

func (v *ResponseData) Error() string

Error returns the error message from the view data model.

func (*ResponseData) Errors

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

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

func (*ResponseData) Get

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

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

func (*ResponseData) GetString

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

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

func (*ResponseData) HasError

func (v *ResponseData) HasError() bool

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

func (*ResponseData) HasErrors

func (v *ResponseData) HasErrors() bool

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

func (*ResponseData) HxNonce

func (v *ResponseData) 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 (*ResponseData) IsBoostedRequest

func (v *ResponseData) IsBoostedRequest() bool

IsBoostedRequest returns true if the request is a boosted request.

func (*ResponseData) IsHtmxRequest

func (v *ResponseData) IsHtmxRequest() bool

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

func (*ResponseData) Nonce

func (v *ResponseData) Nonce() string

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

func (*ResponseData) RequestMethod

func (v *ResponseData) RequestMethod() string

RequestMethod returns the method of the request.

func (*ResponseData) RequestPath

func (v *ResponseData) RequestPath() string

RequestPath returns the path of the request.

func (*ResponseData) SetRequest

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

SetRequest sets the request for the Data instance.

func (*ResponseData) SetTitle

func (v *ResponseData) SetTitle(title string)

SetTitle sets the title of the page.

func (*ResponseData) Title

func (v *ResponseData) Title() string

Title returns the title of the page.

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, it will be prefixed to the template name. e.g., "foo:bar" for a template named "bar" in the "foo" file system.

func (*TemplateManager) LoadTemplates

func (tm *TemplateManager) LoadTemplates() error

LoadTemplates loads the templates from the configured map of file systems and caches them.

func (*TemplateManager) NewResponse

func (tm *TemplateManager) NewResponse() *Response

NewResponse creates a new Response instance with the TemplateManager.

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 `funcs.go` file 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