41 lines
1.1 KiB
Go
41 lines
1.1 KiB
Go
package classes
|
|
|
|
import (
|
|
"strings"
|
|
)
|
|
|
|
// Template placeholders (D-03): the content's title, its own description
|
|
// or excerpt, and the site name.
|
|
const (
|
|
PlaceholderTitle = "%title%"
|
|
PlaceholderDescription = "%description%"
|
|
PlaceholderSite = "%site%"
|
|
)
|
|
|
|
// TemplateVars are the values a template's placeholders take.
|
|
type TemplateVars struct {
|
|
Title string
|
|
Description string
|
|
Site string
|
|
}
|
|
|
|
// templateTrim are the separator characters left at either end when a
|
|
// placeholder renders empty ("About | " without a site name).
|
|
const templateTrim = " \t|-–—·:,"
|
|
|
|
// RenderTemplate fills a title or description template. Runs of
|
|
// whitespace collapse to one space and separators left at either end by an
|
|
// empty placeholder are trimmed. An empty template renders "".
|
|
func RenderTemplate(tpl string, vars TemplateVars) string {
|
|
if strings.TrimSpace(tpl) == "" {
|
|
return ""
|
|
}
|
|
out := strings.NewReplacer(
|
|
PlaceholderTitle, vars.Title,
|
|
PlaceholderDescription, vars.Description,
|
|
PlaceholderSite, vars.Site,
|
|
).Replace(tpl)
|
|
out = strings.Join(strings.Fields(out), " ")
|
|
return strings.Trim(out, templateTrim)
|
|
}
|