2021-12-03 03:11:01 -08:00
|
|
|
package funcmap
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"html/template"
|
|
|
|
"reflect"
|
|
|
|
"strings"
|
|
|
|
|
2022-01-01 07:44:18 -08:00
|
|
|
"github.com/mikestefanello/pagoda/config"
|
2021-12-10 05:33:49 -08:00
|
|
|
|
2021-12-03 03:11:01 -08:00
|
|
|
"github.com/Masterminds/sprig"
|
|
|
|
"github.com/labstack/gommon/random"
|
|
|
|
)
|
|
|
|
|
2021-12-19 13:08:09 -08:00
|
|
|
var (
|
|
|
|
// CacheBuster stores a random string used as a cache buster for static files.
|
|
|
|
CacheBuster = random.String(10)
|
|
|
|
)
|
2021-12-03 03:11:01 -08:00
|
|
|
|
2021-12-19 13:08:09 -08:00
|
|
|
// GetFuncMap provides a template function map
|
2021-12-03 03:11:01 -08:00
|
|
|
func GetFuncMap() template.FuncMap {
|
|
|
|
// See http://masterminds.github.io/sprig/ for available funcs
|
|
|
|
funcMap := sprig.FuncMap()
|
|
|
|
|
|
|
|
// Provide a list of custom functions
|
2021-12-19 13:08:09 -08:00
|
|
|
// Expand this as you add more functions to this package
|
|
|
|
// Avoid using a name already in use by sprig
|
2021-12-03 03:11:01 -08:00
|
|
|
f := template.FuncMap{
|
|
|
|
"hasField": HasField,
|
|
|
|
"file": File,
|
|
|
|
"link": Link,
|
|
|
|
}
|
|
|
|
|
|
|
|
for k, v := range f {
|
|
|
|
funcMap[k] = v
|
|
|
|
}
|
|
|
|
|
|
|
|
return funcMap
|
|
|
|
}
|
|
|
|
|
|
|
|
// HasField checks if an interface contains a given field
|
|
|
|
func HasField(v interface{}, name string) bool {
|
|
|
|
rv := reflect.ValueOf(v)
|
|
|
|
if rv.Kind() == reflect.Ptr {
|
|
|
|
rv = rv.Elem()
|
|
|
|
}
|
|
|
|
if rv.Kind() != reflect.Struct {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return rv.FieldByName(name).IsValid()
|
|
|
|
}
|
|
|
|
|
2021-12-19 13:08:09 -08:00
|
|
|
// File appends a cache buster to a given filepath so it can remain cached until the app is restarted
|
2021-12-03 03:11:01 -08:00
|
|
|
func File(filepath string) string {
|
2021-12-19 13:08:09 -08:00
|
|
|
return fmt.Sprintf("/%s/%s?v=%s", config.StaticPrefix, filepath, CacheBuster)
|
2021-12-03 03:11:01 -08:00
|
|
|
}
|
|
|
|
|
2021-12-19 13:08:09 -08:00
|
|
|
// Link outputs HTML for a link element, providing the ability to dynamically set the active class
|
2021-12-03 03:11:01 -08:00
|
|
|
func Link(url, text, currentPath string, classes ...string) template.HTML {
|
|
|
|
if currentPath == url {
|
2021-12-03 05:49:07 -08:00
|
|
|
classes = append(classes, "is-active")
|
2021-12-03 03:11:01 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
html := fmt.Sprintf(`<a class="%s" href="%s">%s</a>`, strings.Join(classes, " "), url, text)
|
|
|
|
return template.HTML(html)
|
|
|
|
}
|