Added HTMX partial support template rendering.

This commit is contained in:
mikestefanello 2021-12-23 17:09:44 -05:00
parent f115fcb602
commit b2f64b62f4
7 changed files with 126 additions and 60 deletions

View file

@ -36,10 +36,13 @@ func NewController(c *services.Container) Controller {
// RenderPage renders a Page as an HTTP response // RenderPage renders a Page as an HTTP response
func (c *Controller) RenderPage(ctx echo.Context, page Page) error { func (c *Controller) RenderPage(ctx echo.Context, page Page) error {
var buf *bytes.Buffer
var err error
// Page name is required // Page name is required
if page.Name == "" { if page.Name == "" {
ctx.Logger().Error("page render failed due to missing name") ctx.Logger().Error("page render failed due to missing name")
return echo.NewHTTPError(http.StatusInternalServerError, "Internal server error") return echo.NewHTTPError(http.StatusInternalServerError)
} }
// Use the app name in configuration if a value was not set // Use the app name in configuration if a value was not set
@ -47,38 +50,65 @@ func (c *Controller) RenderPage(ctx echo.Context, page Page) error {
page.AppName = c.Container.Config.App.Name page.AppName = c.Container.Config.App.Name
} }
// Parse and execute the templates for the Page // Check if this is an HTMX request
// As mentioned in the documentation for the Page struct, the templates used for the page will be: if page.HTMX.Request.Enabled && !page.HTMX.Request.Boosted {
// 1. The layout/base template specified in Page.Layout // Disable caching
// 2. The content template specified in Page.Name page.Cache.Enabled = false
// 3. All templates within the components directory
// Also included is the function map provided by the funcmap package // Parse and execute
buf, err := c.Container.TemplateRenderer.ParseAndExecute( buf, err = c.Container.TemplateRenderer.ParseAndExecute(
"controller", "page:htmx",
page.Name, page.Name,
page.Layout, "htmx",
[]string{ []string{
fmt.Sprintf("layouts/%s", page.Layout), "htmx",
fmt.Sprintf("pages/%s", page.Name), fmt.Sprintf("pages/%s", page.Name),
}, },
[]string{"components"}, []string{"components"},
page, page,
) )
} else {
// Parse and execute the templates for the Page
// As mentioned in the documentation for the Page struct, the templates used for the page will be:
// 1. The layout/base template specified in Page.Layout
// 2. The content template specified in Page.Name
// 3. All templates within the components directory
// Also included is the function map provided by the funcmap package
buf, err = c.Container.TemplateRenderer.ParseAndExecute(
"page",
page.Name,
page.Layout,
[]string{
fmt.Sprintf("layouts/%s", page.Layout),
fmt.Sprintf("pages/%s", page.Name),
},
[]string{"components"},
page,
)
}
if err != nil { if err != nil {
ctx.Logger().Errorf("failed to parse and execute templates: %v", err) ctx.Logger().Errorf("failed to parse and execute templates: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError, "Internal server error") return echo.NewHTTPError(http.StatusInternalServerError)
} }
// Cache this page, if caching was enabled // Set the status code
c.cachePage(ctx, page, buf) ctx.Response().Status = page.StatusCode
// Set any headers // Set any headers
for k, v := range page.Headers { for k, v := range page.Headers {
ctx.Response().Header().Set(k, v) ctx.Response().Header().Set(k, v)
} }
return ctx.HTMLBlob(page.StatusCode, buf.Bytes()) // Apply the HTMX response, if one
if page.HTMX.Response != nil {
page.HTMX.Response.Apply(ctx)
}
// Cache this page, if caching was enabled
c.cachePage(ctx, page, buf)
return ctx.HTMLBlob(ctx.Response().Status, buf.Bytes())
} }
// cachePage caches the HTML for a given Page if the Page has caching enabled // cachePage caches the HTML for a given Page if the Page has caching enabled
@ -92,6 +122,12 @@ func (c *Controller) cachePage(ctx echo.Context, page Page, html *bytes.Buffer)
page.Cache.Expiration = c.Container.Config.Cache.Expiration.Page page.Cache.Expiration = c.Container.Config.Cache.Expiration.Page
} }
// Extract the headers
headers := make(map[string]string)
for k, v := range ctx.Response().Header() {
headers[k] = v[0]
}
// The request URL is used as the cache key so the middleware can serve the // The request URL is used as the cache key so the middleware can serve the
// cached page on matching requests // cached page on matching requests
key := ctx.Request().URL.String() key := ctx.Request().URL.String()
@ -102,8 +138,8 @@ func (c *Controller) cachePage(ctx echo.Context, page Page, html *bytes.Buffer)
cp := middleware.CachedPage{ cp := middleware.CachedPage{
URL: key, URL: key,
HTML: html.Bytes(), HTML: html.Bytes(),
Headers: page.Headers, Headers: headers,
StatusCode: page.StatusCode, StatusCode: ctx.Response().Status,
} }
err := marshaler.New(c.Container.Cache).Set(ctx.Request().Context(), key, cp, opts) err := marshaler.New(c.Container.Cache).Set(ctx.Request().Context(), key, cp, opts)

View file

@ -67,6 +67,10 @@ func (f FormSubmission) GetFieldStatusClass(fieldName string) string {
return "" return ""
} }
func (f FormSubmission) IsDone() bool {
return f.IsSubmitted && !f.HasErrors()
}
func (f *FormSubmission) setErrorMessages(form interface{}, err error) { func (f *FormSubmission) setErrorMessages(form interface{}, err error) {
// Only this is supported right now // Only this is supported right now
ves, ok := err.(validator.ValidationErrors) ves, ok := err.(validator.ValidationErrors)

View file

@ -6,6 +6,7 @@ import (
"time" "time"
"goweb/context" "goweb/context"
"goweb/htmx"
"goweb/msg" "goweb/msg"
echomw "github.com/labstack/echo/v4/middleware" echomw "github.com/labstack/echo/v4/middleware"
@ -94,6 +95,11 @@ type Page struct {
// This will only be populated if the request ID middleware is in effect for the given request. // This will only be populated if the request ID middleware is in effect for the given request.
RequestID string RequestID string
HTMX struct {
Request htmx.Request
Response *htmx.Response
}
// Cache stores values for caching the response of this page // Cache stores values for caching the response of this page
Cache struct { Cache struct {
// Enabled dictates if the response of this page should be cached. // Enabled dictates if the response of this page should be cached.
@ -133,6 +139,8 @@ func NewPage(ctx echo.Context) Page {
p.IsAuth = true p.IsAuth = true
} }
p.HTMX.Request = htmx.GetRequest(ctx)
return p return p
} }

View file

@ -1,11 +1,8 @@
package routes package routes
import ( import (
"net/http"
"goweb/context" "goweb/context"
"goweb/controller" "goweb/controller"
"goweb/msg"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
) )
@ -43,6 +40,8 @@ func (c *Contact) Post(ctx echo.Context) error {
// return c.Get(ctx) // return c.Get(ctx)
//} //}
// TODO: Error handling w/ HTMX support
// Parse the form values // Parse the form values
var form ContactForm var form ContactForm
if err := ctx.Bind(&form); err != nil { if err := ctx.Bind(&form); err != nil {
@ -55,17 +54,11 @@ func (c *Contact) Post(ctx echo.Context) error {
ctx.Set(context.FormKey, form) ctx.Set(context.FormKey, form)
if form.Submission.HasErrors() { if !form.Submission.HasErrors() {
return c.Get(ctx) if err := c.Container.Mail.Send(ctx, form.Email, "Hello!"); err != nil {
ctx.Logger().Error(err)
}
} }
htmx := controller.GetHTMXRequest(ctx) return c.Get(ctx)
if htmx.Enabled {
return ctx.String(http.StatusOK, "<b>HELLO!</b>")
} else {
msg.Success(ctx, "Thank you for contacting us!")
msg.Info(ctx, "We will respond to you shortly.")
return c.Redirect(ctx, "home")
}
} }

View file

@ -31,7 +31,7 @@ func NewMailClient(cfg *config.Config, templates *TemplateRenderer) (*MailClient
// Send sends an email to a given email address with a given body // Send sends an email to a given email address with a given body
func (c *MailClient) Send(ctx echo.Context, to, body string) error { func (c *MailClient) Send(ctx echo.Context, to, body string) error {
if c.skipSend() { if c.skipSend() {
ctx.Logger().Debugf("skipping email sent to: %s") ctx.Logger().Debugf("skipping email sent to: %s", to)
} }
// TODO: Finish based on your mail sender of choice // TODO: Finish based on your mail sender of choice
@ -43,7 +43,7 @@ func (c *MailClient) Send(ctx echo.Context, to, body string) error {
// The funcmap will be automatically added to the template and the data will be passed in. // The funcmap will be automatically added to the template and the data will be passed in.
func (c *MailClient) SendTemplate(ctx echo.Context, to, template string, data interface{}) error { func (c *MailClient) SendTemplate(ctx echo.Context, to, template string, data interface{}) error {
if c.skipSend() { if c.skipSend() {
ctx.Logger().Debugf("skipping template email sent to: %s") ctx.Logger().Debugf("skipping template email sent to: %s", to)
} }
// Parse and execute template // Parse and execute template

1
templates/htmx.gohtml Normal file
View file

@ -0,0 +1 @@
{{template "content" .}}

View file

@ -1,27 +1,51 @@
{{define "content"}} {{define "content"}}
<form id="contact" method="post" > {{- if not (eq .HTMX.Request.Target "contact")}}
<div class="field"> <article class="message is-link">
<label for="email" class="label">Email address</label> <div class="message-body">
<div class="control"> <p>This is an example of a form with inline, server-side validation and HTMX-powered AJAX submissions without writing a single line of JavaScript.</p>
<input id="email" name="email" type="email" class="input {{.Form.Submission.GetFieldStatusClass "email"}}" value="{{.Form.Email}}"> <p>Only the form below will update async upon submission.</p>
</div> </div>
{{template "field-errors" (.Form.Submission.GetFieldErrors "email")}} </article>
</div> {{- end}}
<div class="field"> {{template "form" .}}
<label for="message" class="label">Message</label> {{end}}
<div class="control">
<textarea id="message" name="message" class="textarea {{.Form.Submission.GetFieldStatusClass "message"}}">{{.Form.Message}}</textarea> {{define "form"}}
</div> {{- if .Form.Submission.IsDone}}
{{template "field-errors" (.Form.Submission.GetFieldErrors "message")}} <article class="message is-large is-success">
</div> <div class="message-header">
<p>Thank you!</p>
<div class="field is-grouped"> </div>
<div class="control"> <div class="message-body">
<button class="button is-link">Submit</button> No email was actually sent but this entire operation was handled server-side and degrades without JavaScript enabled.
</div> </div>
</div> </article>
{{- else}}
{{template "csrf" .}} <form id="contact" method="post" hx-post>
</form> <div class="field">
<label for="email" class="label">Email address</label>
<div class="control">
<input id="email" name="email" type="email" class="input {{.Form.Submission.GetFieldStatusClass "email"}}" value="{{.Form.Email}}">
</div>
{{template "field-errors" (.Form.Submission.GetFieldErrors "email")}}
</div>
<div class="field">
<label for="message" class="label">Message</label>
<div class="control">
<textarea id="message" name="message" class="textarea {{.Form.Submission.GetFieldStatusClass "message"}}">{{.Form.Message}}</textarea>
</div>
{{template "field-errors" (.Form.Submission.GetFieldErrors "message")}}
</div>
<div class="field is-grouped">
<div class="control">
<button class="button is-link">Submit</button>
</div>
</div>
{{template "csrf" .}}
</form>
{{- end}}
{{end}} {{end}}