goweb/template/html/option.go

71 lines
1.5 KiB
Go

package html
import "html/template"
// Options are configuration options for the template service
type Options struct {
Helpers template.FuncMap
PoolSize int
DevMode bool
}
// OptionFunc configures options for the template service
type OptionFunc func(*Options)
// WithDefaultHelpers configures the template service
// to expose the default helpers
func WithDefaultHelpers() OptionFunc {
return func(opts *Options) {
helpers := template.FuncMap{
"dump": dump,
"ellipsis": ellipsis,
"map": customMap,
"default": defaultVal,
"inc": increment,
"has": has,
}
for name, fn := range helpers {
WithHelper(name, fn)(opts)
}
}
}
// WithHelper configures the template service
// to expose the default helpers
func WithHelper(name string, fn interface{}) OptionFunc {
return func(opts *Options) {
if opts.Helpers == nil {
opts.Helpers = make(template.FuncMap)
}
opts.Helpers[name] = fn
}
}
// WithPoolSize configures the template service
// to use the given pool size
func WithPoolSize(size int) OptionFunc {
return func(opts *Options) {
opts.PoolSize = size
}
}
// WithDevMode configures the template service
// to use the development mode (auto reload of templates).
func WithDevMode(enabled bool) OptionFunc {
return func(opts *Options) {
opts.DevMode = enabled
}
}
func defaultOptions() *Options {
options := &Options{}
funcs := []OptionFunc{
WithPoolSize(64),
WithDefaultHelpers(),
}
for _, f := range funcs {
f(options)
}
return options
}