tman

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2024 License: MIT Imports: 15 Imported by: 0

README

TMan

This is a template manager for go. Because a package named templatemanager seemed too long.

Goals

  1. Create a nice wrapper around the go template library.
  2. Provide caching while in production; yet allow for hot reloading while in development
    • Caching can happen in two tiers, an embedded fs.FS and parsed templates
  3. Provide a cleaner more simple api than fazer
  4. Provide a merge method
  5. Provide consistent errors, success, config, page metadata to the parse context
  6. Add a session manager to the renderer
  7. Common template functions
  8. Have a page type with html page metadata
  9. Have a key based access to the parsed template
  10. Include partial templates

Thoughts

The template library has a method to define specific templates and handle the caching. However this flies in the face of easily being able to dynamically parsing in dev mode.

Notes about embed

One of the main reasons for making tman is to make use of the go 1.16 embed directive.

My previous library used a directory, and dynamically rewrote the template paths as needed. I wanted a cleaner approach than that for this library.

One of my main goals is goal 2 from above. To do that, I've found there are a few things to be aware of with the embed library.

To facilitate goal to, I have a production flag that can be toggled via environment variables. Then I just check if in production and use the appropriate fs.FS implementation:

//go:embed static var embeddedFS // Now to referenced the embedded directory just like the os.DirFS call below subFS, _ := fs.Sub(embeddedFS, "static/tpls")

var templateFS fs.FS if Prod { templateFS = subFS } else { templateFS = os.DirFS("static/tpls") }

Things to Know
  • Your embedded directory must be at the same level or below the source file with the embed directive. Therefore, no .. or . in the directive.

Documentation

Index

Constants

View Source
const (
	DefaultPageGlob    = "*.page.*"
	DefaultLayoutGlob  = "*.layout.*"
	DefaultPartialGlob = "*.partial.*"
)

Variables

View Source
var ErrorMessageNotFound = errors.New("error message not found")
View Source
var ErrorNoTemplate = errors.New("error no template")
View Source
var ErrorNoTemplates = errors.New("error no templates")
View Source
var ErrorParsingMessage = errors.New("error parsing message")
View Source
var ErrorParsingPartial = errors.New("error parsing partial")
View Source
var ErrorPartialNotFound = errors.New("partial not found")

Functions

func MRender

func MRender(in string) template.HTML

func SafeHTML

func SafeHTML(input string) template.HTML

func SetLayoutGlob added in v0.6.0

func SetLayoutGlob(layoutGlob string) func(v *Vault)

func SetPageGlob added in v0.6.0

func SetPageGlob(pageGlob string) func(v *Vault)

func SetPartialGlob added in v0.6.0

func SetPartialGlob(partialGlob string) func(v *Vault)

Types

type Asset

type Asset struct {
	Key      string `json:"key"`
	DevPath  string `json:"devPath"`
	ProdPath string `json:"prodPath"`
}

func NewAsset added in v0.4.2

func NewAsset(key, devPath, prodPath string) Asset

type FlashAdapter added in v0.5.0

type FlashAdapter interface {
	SetErrorFlash(w http.ResponseWriter, r *http.Request, msg string) error
	SetSuccessFlash(w http.ResponseWriter, r *http.Request, msg string) error
	GetFlashMessages(w http.ResponseWriter, r *http.Request) (e string, s string, err error)
}

type Merge

type Merge func(r *http.Request, data map[string]interface{})

type Message

type Message struct {
	Key         string   `json:"key"`
	PlainTPLS   []string `json:"plainTpls"`
	CachedPlain *txttpl.Template
	HtmlTPLS    []string `json:"htmlTpls"`
	CachedHtml  *template.Template
}

func NewHtmlMessage added in v0.4.2

func NewHtmlMessage(key string, htmlTpls ...string) *Message

func NewPlainMessage added in v0.4.2

func NewPlainMessage(key string, plainTpls ...string) *Message

type Page

type Page struct {
	Key string `json:"key"`

	Tpls   []string `json:"tpls"`
	Cached *template.Template

	Title              string `json:"title"`
	Description        string `json:"description"`
	Canonical          string `json:"canonical"`
	OgURL              string `json:"ogurl"`
	OgTitle            string `json:"ogtitle"`
	OgDescription      string `json:"ogdescription"`
	OgImage            string `json:"ogimage"`
	OgImageType        string `json:"ogimagetype"`
	OgImageWidth       string `json:"ogimagewidth"`
	OgImageHeight      string `json:"ogimageheight"`
	FbAppID            string `json:"fbappid"`
	OgType             string `json:"ogtype"`
	OgLocale           string `json:"oglocale"`
	TwitterCard        string `json:"twittercard"`
	TwitterSite        string `json:"twittersite"`
	TwitterTitle       string `json:"twittertitle"`
	TwitterDescription string `json:"twitterdescription"`
	TwitterCreator     string `json:"twittercreator"`
	TwitterImage       string `json:"twitterimage"`
	// contains filtered or unexported fields
}

func NewPage added in v0.4.2

func NewPage(key string, tpls ...string) *Page

func (Page) GetDescription

func (p Page) GetDescription(def string) string

GetDescription returns page description, intended to be called from the template with a default value

func (Page) GetFbAppId

func (p Page) GetFbAppId(def string) string

GetFbAppId returns the fb app id or the default value passed in

func (Page) GetOgDescription

func (p Page) GetOgDescription(def string) string

GetOgDescription returns the open graph description, the regular description, or the default value passed in

func (Page) GetOgImage

func (p Page) GetOgImage(def string) string

GetOgImage returns the open graph image or the default value passed in

func (Page) GetOgLocale

func (p Page) GetOgLocale() string

GetOgLocale returns the open graph locale or the default locale

func (Page) GetOgTitle

func (p Page) GetOgTitle(def string) string

GetOgTitle returns the open graph title for the page, or the regular title, or the default value passed in

func (Page) GetOgType

func (p Page) GetOgType() string

GetOgType returns the open graph type or the default website

func (Page) GetOgUrl

func (p Page) GetOgUrl() string

GetOgUrl returns the open graph url or the canonical url

func (Page) GetTitle

func (p Page) GetTitle(def string) string

GetTitle returns the page title, intended to be called from the template with a default value

func (Page) GetTwitterCard

func (p Page) GetTwitterCard(def string) string

GetTwitterCard returns the twitter card summary

func (Page) GetTwitterCreator

func (p Page) GetTwitterCreator(def string) string

GetTwitterCreator returns the twitter creator or default

func (Page) GetTwitterDescription

func (p Page) GetTwitterDescription(def string) string

GetTwitterDescription returns the twitter description or the page description or the default

func (Page) GetTwitterImage

func (p Page) GetTwitterImage(def string) string

GetTwitterImage returns the twitter image or default

func (Page) GetTwitterSite

func (p Page) GetTwitterSite(def string) string

GetTwitterSite returns the twitter site or default. i.e. @KendellFab

func (Page) GetTwitterTitle

func (p Page) GetTwitterTitle(def string) string

GetTwitterTitle returns the twitter title or the page title or the default

func (*Page) SetOptions added in v0.4.2

func (p *Page) SetOptions(opts ...PageOpts) *Page

type PageOpts added in v0.4.2

type PageOpts func(page *Page)

func SetDescription added in v0.4.2

func SetDescription(description string) PageOpts

func SetTitle added in v0.4.2

func SetTitle(title string) PageOpts

type Partial

type Partial struct {
	Key    string
	Tpl    string `json:"tpl"`
	Cached *template.Template
}

func NewPartial added in v0.4.2

func NewPartial(key string, tpl string) *Partial

type Payload added in v0.6.2

type Payload struct {
	Config         any
	Request        *http.Request
	Page           *Page
	FlashError     string
	FlashSuccess   string
	FlashLoadError string
	Merge          map[string]any
	// contains filtered or unexported fields
}

type Vault added in v0.4.0

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

Vault is a wrapper around the go template library. The pageFS parameter is to be the root file system used where all of the page & partial tpls reference from

func NewVault added in v0.4.0

func NewVault(flashAdapter FlashAdapter, prod bool, config interface{}, pageFs fs.FS, opts ...VaultConfig) *Vault

NewVault creates a new Vault instance.

func (*Vault) AddJsonManifest added in v0.4.0

func (v *Vault) AddJsonManifest(input string) error

AddJsonManifest is a json representation of the pages, partials, messages, and assets to be managed by this Vault instance It is to be formatted as

{
		"pages": [],
		"partials": [],
		"messages": [],
		"js": [],
		"css": [],
		"img": []
	}

It is recommended that this use the embed directive to get a string from the filesystem. However it could be stored as a string and passed in.

func (*Vault) AutoRegisterPages added in v0.6.0

func (v *Vault) AutoRegisterPages()

AutoRegisterPages will look for pages, layouts, and partials based upon the glob patterns that are set. You need your templates setup properly for this to work, but it does make it easier to get started. base.layout.gohtml {{define "base"}} <!DOCTYPE html>

<html lang="en">
	<head>
		<title>{{block "title" .}}Title{{end}}</title>
	</head>
	<body>
		{{block "content" .}}{{end}}
	</body>
</html>

{{end}} # Ends defining base template

index.page.gohtml {{template "base" .}}

{{define "title"}}Page Title{{end}} {{define "content"}}

	<h1>Page</h1>
{{end}}

func (*Vault) GetCssPath added in v0.4.0

func (v *Vault) GetCssPath(key string) string

func (*Vault) GetImgPath added in v0.4.0

func (v *Vault) GetImgPath(key string) string

func (*Vault) GetJsPath added in v0.4.0

func (v *Vault) GetJsPath(key string) string

func (*Vault) Partial added in v0.4.0

func (v *Vault) Partial(name string, payload interface{}) (template.HTML, error)

Partial allows a partial to be loaded within the template. Use: {{ partial "key" . }}

func (*Vault) Redirect added in v0.4.0

func (v *Vault) Redirect(w http.ResponseWriter, r *http.Request, url string)

Redirect returns a redirect with http.StatusSeeOther

func (*Vault) RedirectCode added in v0.4.0

func (v *Vault) RedirectCode(w http.ResponseWriter, r *http.Request, url string, code int)

RedirectCode returns a redirect with given http status

func (*Vault) RegisterCSS added in v0.4.0

func (v *Vault) RegisterCSS(css Asset)

func (*Vault) RegisterImg added in v0.4.0

func (v *Vault) RegisterImg(img Asset)

func (*Vault) RegisterJS added in v0.4.0

func (v *Vault) RegisterJS(js Asset)

func (*Vault) RegisterMerge added in v0.4.0

func (v *Vault) RegisterMerge(merge Merge)

func (*Vault) RegisterMessage added in v0.4.0

func (v *Vault) RegisterMessage(message *Message)

func (*Vault) RegisterMessageFS added in v0.4.0

func (v *Vault) RegisterMessageFS(message fs.FS)

RegisterMessageFS takes a file system where the message tpls reference from

func (*Vault) RegisterPage added in v0.4.0

func (v *Vault) RegisterPage(page *Page)

func (*Vault) RegisterPartial added in v0.4.0

func (v *Vault) RegisterPartial(partial *Partial)

func (*Vault) RegisterTemplateFunc added in v0.4.0

func (v *Vault) RegisterTemplateFunc(key string, fn any)

func (*Vault) Render added in v0.6.2

func (v *Vault) Render(w http.ResponseWriter, r *http.Request, key string, data any)

func (*Vault) RenderJson added in v0.4.0

func (v *Vault) RenderJson(w http.ResponseWriter, data any)

RenderJson is a shortcut method for rendering json to the response

func (*Vault) RenderJsonWithCode added in v0.7.0

func (v *Vault) RenderJsonWithCode(code int, w http.ResponseWriter, data any)

func (*Vault) RenderMessageHtml added in v0.4.0

func (v *Vault) RenderMessageHtml(w io.Writer, key string, data map[string]interface{}) error

func (*Vault) RenderMessagePlain added in v0.4.0

func (v *Vault) RenderMessagePlain(w io.Writer, key string, data map[string]interface{}) error

func (*Vault) RenderPage added in v0.4.0

func (v *Vault) RenderPage(w http.ResponseWriter, r *http.Request, key string, data map[string]interface{})

func (*Vault) SetErrorFlash added in v0.4.0

func (v *Vault) SetErrorFlash(w http.ResponseWriter, r *http.Request, message string)

SetErrorFlash sets a flash error message if the fazer.store is not nil

func (*Vault) SetSuccessFlash added in v0.4.0

func (v *Vault) SetSuccessFlash(w http.ResponseWriter, r *http.Request, message string)

SetSuccessFlash sets a flash success message if the fazer.store is not nil

type VaultConfig added in v0.6.0

type VaultConfig func(*Vault)

Directories

Path Synopsis
scsadapter module

Jump to

Keyboard shortcuts

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