Skip to content

Commit

Permalink
Move templates to use const naming
Browse files Browse the repository at this point in the history
  • Loading branch information
jbowa committed Mar 9, 2024
1 parent 33259c7 commit b09649c
Show file tree
Hide file tree
Showing 17 changed files with 80 additions and 51 deletions.
6 changes: 3 additions & 3 deletions pkg/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (c *Controller) RenderPage(ctx echo.Context, page Page) error {
buf, err = c.Container.TemplateRenderer.
Parse().
Group("page:htmx").
Key(page.Name).
Key(string(page.Name)).
Base("htmx").
Files(
"htmx",
Expand All @@ -76,8 +76,8 @@ func (c *Controller) RenderPage(ctx echo.Context, page Page) error {
buf, err = c.Container.TemplateRenderer.
Parse().
Group("page").
Key(page.Name).
Base(page.Layout).
Key(string(page.Name)).
Base(string(page.Layout)).
Files(
fmt.Sprintf("layouts/%s", page.Layout),
fmt.Sprintf("pages/%s", page.Name),
Expand Down
14 changes: 8 additions & 6 deletions pkg/controller/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package controller

import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
Expand Down Expand Up @@ -78,14 +79,15 @@ func TestController_RenderPage(t *testing.T) {
}

// Check the template cache
parsed, err := c.TemplateRenderer.Load("page", p.Name)
parsed, err := c.TemplateRenderer.Load("page", string(p.Name))
assert.NoError(t, err)

// Check that all expected templates were parsed.
// This includes the name, layout and all components.
expectedTemplates := make(map[string]bool)
expectedTemplates[p.Name+config.TemplateExt] = true
expectedTemplates[p.Layout+config.TemplateExt] = true
expectedTemplates[fmt.Sprintf("%s%s", p.Name, config.TemplateExt)] = true
expectedTemplates[fmt.Sprintf("%s%s", p.Layout, config.TemplateExt)] = true

components, err := templates.Get().ReadDir("components")
require.NoError(t, err)

Expand Down Expand Up @@ -114,12 +116,12 @@ func TestController_RenderPage(t *testing.T) {
assert.Equal(t, "true", ctx.Response().Header().Get(htmx.HeaderRedirect))

// Check the parsed template cache
parsed, err := c.TemplateRenderer.Load("page:htmx", p.Name)
parsed, err := c.TemplateRenderer.Load("page:htmx", string(p.Name))
assert.NoError(t, err)

// Check that all teh expected templates where parsed
// Check that all the expected templates where parsed
expectedTemplates := make(map[string]bool)
expectedTemplates[p.Name+config.TemplateExt] = true
expectedTemplates[fmt.Sprintf("%s%s", p.Name, config.TemplateExt)] = true
expectedTemplates["htmx"+config.TemplateExt] = true
components, err := templates.Get().ReadDir("components")
require.NoError(t, err)
Expand Down
7 changes: 4 additions & 3 deletions pkg/controller/page.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
echomw "github.com/labstack/echo/v4/middleware"

"github.com/tiny-blob/tinyblob/pkg/htmx"
"github.com/tiny-blob/tinyblob/templates"
)

// Page consists of all data that will be used to render a page response for a
Expand Down Expand Up @@ -41,20 +42,20 @@ type Page struct {
// This should match a template file located within the layouts directory
// inside the templates directory. The template extension should not be
// included in this value.
Layout string
Layout templates.Layout
// Name stores the name of the page as well as the name of the template file
// which will be used to render the content portion of the layout template.
// This should match a template file located within the pages directory inside
// the templates directory. The template extension should not be included in
// this value.
Name string
Name templates.Page
// RequestID stores the ID of the given request.
// This will only be populated if the request ID middleware is in effect for the given request.
RequestID string
// StatusCode stores the HTTP status code to be returned.
StatusCode int
// ToURL is a function to convert a route name and optional route parameters to a URL
ToURL func(name string, params ...interface{}) string
ToURL func(name string, params ...any) string
Path string
// URL stores the URL of the current request
URL string
Expand Down
2 changes: 1 addition & 1 deletion pkg/funcmap/funcmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func GetFuncMap() template.FuncMap {
}

// HasField checks if an interface contains a given field.
func HasField(v interface{}, name string) bool {
func HasField(v any, name string) bool {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
Expand Down
2 changes: 1 addition & 1 deletion pkg/funcmap/funcmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func TestLink(t *testing.T) {
assert.Equal(t, expected, link)
}

func TestGetFuncMap(t *testing.T) {
func TestFile(t *testing.T) {
fileName := "favicon.ico"
file := File(fileName)
expected := fmt.Sprintf("/%s/%s?v=%s", config.StaticPrefix, fileName, CacheBuster)
Expand Down
5 changes: 3 additions & 2 deletions pkg/routes/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/tiny-blob/tinyblob/pkg/context"
"github.com/tiny-blob/tinyblob/pkg/controller"
"github.com/tiny-blob/tinyblob/templates"
)

type errorHandler struct {
Expand All @@ -30,9 +31,9 @@ func (e *errorHandler) Get(err error, ctx echo.Context) {
}

page := controller.NewPage(ctx)
page.Layout = "main"
page.Title = http.StatusText(code)
page.Name = "error"
page.Layout = templates.LayoutMain
page.Name = templates.PageError
page.StatusCode = code
page.HTMX.Request.Enabled = false

Expand Down
23 changes: 10 additions & 13 deletions pkg/routes/home.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"github.com/labstack/echo/v4"

"github.com/tiny-blob/tinyblob/pkg/controller"
"github.com/tiny-blob/tinyblob/templates"
)

type (
Expand All @@ -15,21 +16,17 @@ type (
func (c *home) Get(ctx echo.Context) error {
page := controller.NewPage(ctx)
page.Cache.Enabled = true
page.Layout = "main"
page.Name = "home"
page.Metatags.Description = "Instantly execute complex crypto strategies at lightning speed."
page.Layout = templates.LayoutMain
page.Name = templates.PageHome
page.Metatags.Description = "A Player vs Player decentralized prediction market "
page.Metatags.Keywords = []string{
"Crypto trading",
"Solana trading",
"Automated trading",
"Lightning-fast transactions",
"Seamless execution",
"Crypto strategies",
"Drag and drop builder",
"Signal trading",
"Trade executor",
"Crypto",
"PvP trading",
"Decentralized",
"Bitcoin",
"PvP prediction market",
}
page.Title = "Crypto tools for professionals"
page.Title = "A PvP prediction marketplace"

return c.RenderPage(ctx, page)
}
6 changes: 5 additions & 1 deletion pkg/routes/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import (
"github.com/tiny-blob/tinyblob/pkg/services"
)

const (
routeNameHome = "home"
)

// BuildRouter builds the router.
func BuildRouter(c *services.Container) {
// Enable cache control for static files.
Expand Down Expand Up @@ -70,5 +74,5 @@ func BuildRouter(c *services.Container) {

func publicRoutes(c *services.Container, g *echo.Group, ctr controller.Controller) {
home := home{Controller: ctr}
g.GET("/", home.Get).Name = "home"
g.GET("/", home.Get).Name = routeNameHome
}
7 changes: 7 additions & 0 deletions pkg/routes/routes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package routes

import "testing"

func TestRoutes(t *testing.T) {
t.Skip("TODO: Implement TestRoutes")
}
10 changes: 5 additions & 5 deletions pkg/services/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ type (
client *CacheClient
group string
key string
dataType interface{}
dataType any
}

// cacheSet handles chainable cache set operations
cacheSet struct {
client *CacheClient
data interface{}
data any
expiration time.Duration
group string
key string
Expand Down Expand Up @@ -96,13 +96,13 @@ func (c *CacheClient) Close() error {
}

// Data sets the data to the cache
func (c *cacheSet) Data(data interface{}) *cacheSet {
func (c *cacheSet) Data(data any) *cacheSet {
c.data = data
return c
}

// Fetch retrieves the data from the cache
func (c *cacheGet) Fetch(ctx context.Context) (interface{}, error) {
func (c *cacheGet) Fetch(ctx context.Context) (any, error) {
if c.key == "" {
return nil, errors.New("no cache key provided")
}
Expand Down Expand Up @@ -225,7 +225,7 @@ func (c *cacheSet) Tags(tags ...string) *cacheSet {
}

// Type set the cache type for the expected data
func (c *cacheGet) Type(expectedType interface{}) *cacheGet {
func (c *cacheGet) Type(expectedType any) *cacheGet {
c.dataType = expectedType
return c
}
4 changes: 2 additions & 2 deletions pkg/services/template_renderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func (t *templateBuilder) Directories(directories ...string) *templateBuilder {
}

// Execute executes a template with the given data and returns the output
func (t *TemplateParsed) Execute(data interface{}) (*bytes.Buffer, error) {
func (t *TemplateParsed) Execute(data any) (*bytes.Buffer, error) {
if t.Template == nil {
return nil, errors.New("cannot execute template: template not initialized")
}
Expand All @@ -89,7 +89,7 @@ func (t *TemplateParsed) Execute(data interface{}) (*bytes.Buffer, error) {

// Execute executes a template with the given data
// If the template has not been cached, it will be parsed and cached.
func (t *templateBuilder) Execute(data interface{}) (*bytes.Buffer, error) {
func (t *templateBuilder) Execute(data any) (*bytes.Buffer, error) {
tp, err := t.Store()
if err != nil {
return nil, err
Expand Down
2 changes: 1 addition & 1 deletion pkg/services/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func NewValidator() *Validator {
}
}

func (v *Validator) Validate(i interface{}) error {
func (v *Validator) Validate(i any) error {
if err := v.validator.Struct(i); err != nil {
return err
}
Expand Down
4 changes: 2 additions & 2 deletions templates/layouts/main.tmpl
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<!DOCTYPE html>
<html lang="en" style="height:100vh;background:#fff;">
<html lang="en" style="height:100vh;background:rgba(55,55,55,.03);">
<head>
{{template "metatags" .}}
{{template "css" .}}
{{template "js" .}}
</head>
<body class="min-h-full h-full bg-white px-4 sm:px-8 md:px-12 py-2 sm:py-4 md:py-6">
<body class="min-h-full h-full bg-[rgba(55,55,55,.03)] px-4 sm:px-8 md:px-12 py-2 sm:py-4 md:py-6">
{{template "content" .}}
</body>
</html>
6 changes: 3 additions & 3 deletions templates/pages/error.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
<p>You’re not authorized to view the requested page</p>
{{else if eq .StatusCode 404}}
<div>
<h1 class="text-white text-8xl">404</h1>
<p class="text-white">Click {{link (call .ToURL "home") "here" .Path}} to return home</p>
<h1 class="text-black text-8xl">404</h1>
<p class="text-black">Click {{link (call .ToURL "home") "here" .Path}} to return home</p>
</div>
{{else}}
<p>Something went wrong. Our engineers have been notified.</>
{{end}}
</main>
{{end}}
{{end}}
14 changes: 8 additions & 6 deletions templates/pages/home.tmpl
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
{{define "content"}}
<div class="h-full w-full grid grid-rows-[auto_1fr_auto]">
{{template "header" .}}
<main class="flex flex-col flex-1 sm:py-4 py-6 sm:py-10">
<div>Home</div>
<main class="flex flex-col flex-1 sm:py-4 py-6 sm:py-10 items-center justify-center">
<div class="text-slate-400 text-sm sm:text-sm bg-purple-100">
Soon.
</div>
</main>
{{template "footer" .}}
</div>
Expand All @@ -14,18 +16,18 @@
TinyBlob
</h2>
<div class="text-black font-medium text-base select-none">
Launch app
{{link (call .ToURL "dashboard") "Launch App" .Path}}
</div>
</header>
{{end}}

{{define "footer"}}
<footer class="w-full h-full flex justify-between items-center">
<div class="text-slate-400 text-sm sm:text-sm mb-2">
About
</div>
<span class="text-slate-400 text-sm sm:text-sm select-none">
© TinyBlob Labs, 2024
</span>
<div class="text-gray-400 text-sm sm:text-sm mb-2 bg-slate-200 px-3 py-2 rounded-2xl">
About
</div>
</footer>
{{end}}
14 changes: 14 additions & 0 deletions templates/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,20 @@ import (
"runtime"
)

type (
Layout string
Page string
)

const (
LayoutMain Layout = "main"
)

const (
PageError Page = "error"
PageHome Page = "home"
)

//go:embed *
var templates embed.FS

Expand Down
5 changes: 3 additions & 2 deletions templates/templates_test.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
package templates

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"
)

func TestGo(t *testing.T) {
_, err := Get().Open("pages/home.tmpl")
_, err := Get().Open(fmt.Sprintf("pages/%s.tmpl", PageHome))
require.NoError(t, err)
}

func TestGetOS(t *testing.T) {
_, err := GetOS().Open("pages/home.tmpl")
_, err := GetOS().Open(fmt.Sprintf("pages/%s.tmpl", PageHome))
require.NoError(t, err)
}

0 comments on commit b09649c

Please sign in to comment.