tmplfuncs

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2026 License: MIT Imports: 6 Imported by: 0

README

tmplfuncs

tmplfuncs is a small helper library for Go text/template and html/template templates.

It provides reusable, pipeline-friendly template functions for JSON rendering, inline conditionals, defaults, coalescing, optional formatted output, time formatting, string normalization, prefixes/suffixes, and durations.

It intentionally avoids locale-dependent helpers such as ago, because human-readable relative time usually needs translation and project-specific wording.

Install

go get github.com/containeroo/tmplfuncs

Register all helpers

package main

import (
	"text/template"

	"github.com/containeroo/tmplfuncs"
)

func main() {
	tmpl, err := template.New("message").
		Funcs(tmplfuncs.FuncMap()).
		Parse(`{{ .Title | json }}`)
	_ = tmpl
	_ = err
}

Register selected helpers

FuncMap accepts optional helper identifiers. When no helpers are passed, all helpers are registered. When helpers are passed, only those helpers are registered.

package main

import (
	"text/template"

	"github.com/containeroo/tmplfuncs"
)

func main() {
	tmpl, err := template.New("message").
		Funcs(tmplfuncs.FuncMap(
			tmplfuncs.JSON,
			tmplfuncs.When,
			tmplfuncs.Default,
			tmplfuncs.Optional,
		)).
		Parse(`{{ when .Resolved "up" "down" }}{{ .StatusURL | optional " %s" }}`)
	_ = tmpl
	_ = err
}

FuncMap panics when an unknown helper identifier is passed. Use FuncMapE when you want an error instead:

funcs, err := tmplfuncs.FuncMapE(tmplfuncs.JSON, tmplfuncs.Optional)

Use individual helper functions

The helper functions registered by FuncMap are exported, so you can register them under your own names or combine them with project-specific helpers.

myFuncMap := template.FuncMap{
	"customDefault": tmplfuncs.DefaultValue,
	"json":          tmplfuncs.JSONValue,
}

Internal support helpers are intentionally not part of the public API.

Helpers

Helper Function name in templates Go function Description
JSON json JSONValue Render a value as a JSON literal.
When when WhenValue Return one of two values based on truthiness.
Default default DefaultValue Return a fallback for empty values.
Coalesce coalesce CoalesceValue Return the first non-empty value.
Optional optional OptionalValue Render formatted text when all values are set.
FormatTime formatTime FormatTimeValue Format a time value with a Go layout.
Trim trim TrimValue Trim surrounding whitespace.
Upper upper UpperValue Convert text to uppercase.
Lower lower LowerValue Convert text to lowercase.
WithPrefix withPrefix WithPrefixValue Prepend a prefix when missing.
WithSuffix withSuffix WithSuffixValue Append a suffix when missing.
Duration duration DurationValue Render a duration as a Go duration string.

Template examples

JSON

Use json when rendering dynamic values into JSON templates.

{
  "text": {{ .Text | json }},
  "status": {{ .Status | json }}
}
Inline conditionals

when returns the second argument when the condition is truthy, otherwise the third argument.

{{ when .Resolved "Resolved at" "Notified at" }}
{{ when .Status "has status" "missing status" }}
Defaults

default supports direct and pipeline usage.

{{ default "unknown" .CheckInName }}
{{ .CheckInName | default "unknown" }}

Empty means nil, false, zero numbers, empty strings, empty arrays, empty maps, empty slices, empty channels, nil pointers/interfaces, and other Go zero values.

Coalescing

coalesce returns the first non-empty value.

{{ coalesce .Title .Name "unknown" }}
Optional formatted output

optional renders an empty string when the format is empty, no values are provided, or any value is empty.

{{ optional "Status URL: %s" .App.StatusURL }}
{{ optional "%s: %s" .Label .Value }}
{{ .App.StatusURL | optional "\n\n*Status URL:* %s" }}

Values are converted to strings and trimmed before formatting.

Time formatting

formatTime accepts time.Time, *time.Time, or an RFC3339/RFC3339Nano string.

{{ .ExpectedBy | formatTime "2006-01-02 15:04:05 MST" }}
Prefix and suffix helpers
{{ .CustomData.channel | default "alertmanager" | withPrefix "#" }}
{{ .Path | withSuffix "/" }}
Duration

duration accepts time.Duration, *time.Duration, or a duration string accepted by time.ParseDuration.

{{ .AlertingDelay | duration }}

API

type Helper string

const (
	JSON       Helper = "json"
	When       Helper = "when"
	Default    Helper = "default"
	Coalesce   Helper = "coalesce"
	Optional   Helper = "optional"
	FormatTime Helper = "formatTime"
	Trim       Helper = "trim"
	Upper      Helper = "upper"
	Lower      Helper = "lower"
	WithPrefix Helper = "withPrefix"
	WithSuffix Helper = "withSuffix"
	Duration   Helper = "duration"
)

func All() []Helper
func FuncMap(helpers ...Helper) template.FuncMap
func FuncMapE(helpers ...Helper) (template.FuncMap, error)

func JSONValue(value any) (string, error)
func WhenValue(condition, trueValue, falseValue any) any
func DefaultValue(fallback, value any) any
func CoalesceValue(values ...any) any
func OptionalValue(format string, values ...any) string
func FormatTimeValue(layout string, value any) (string, error)
func TrimValue(value any) string
func UpperValue(value any) string
func LowerValue(value any) string
func WithPrefixValue(prefix string, value any) string
func WithSuffixValue(suffix string, value any) string
func DurationValue(value any) (string, error)

Compatibility

The module targets Go 1.23 or newer.

The helpers work with both text/template and html/template because both accept template.FuncMap values with the same underlying type.

License

This project is licensed under the Apache 2.0 License. See the LICENSE file for details.

Documentation

Overview

Package tmplfuncs provides small, reusable helper functions for Go templates.

The helpers are designed for use with text/template and html/template. They are pipeline-friendly where that makes templates easier to read.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CoalesceValue

func CoalesceValue(values ...any) any

CoalesceValue returns the first non-empty value.

Empty follows the same rules as DefaultValue.

{{ coalesce .Title .Name "unknown" }}

func DefaultValue

func DefaultValue(fallback, value any) any

DefaultValue returns fallback when value is empty.

Empty follows the same rules as template helpers: nil, false, zero numbers, empty strings, empty arrays, empty maps, empty slices, empty channels, nil pointers/interfaces, and other Go zero values are empty.

The argument order supports both direct and pipeline usage:

{{ default "fallback" .Value }}
{{ .Value | default "fallback" }}

func DurationValue

func DurationValue(value any) (string, error)

DurationValue renders a duration value as a Go duration string.

The value may be time.Duration, *time.Duration, or a string accepted by time.ParseDuration.

{{ .AlertingDelay | duration }}

func FormatTimeValue

func FormatTimeValue(layout string, value any) (string, error)

FormatTimeValue formats a time value with layout.

The value may be time.Time, *time.Time, or an RFC3339/RFC3339Nano string. The argument order supports both direct and pipeline usage:

{{ formatTime "2006-01-02 15:04:05 MST" .ExpectedBy }}
{{ .ExpectedBy | formatTime "2006-01-02 15:04:05 MST" }}

func FuncMap

func FuncMap(helpers ...Helper) template.FuncMap

FuncMap returns a template.FuncMap containing the selected helpers.

When called without arguments, FuncMap returns all helpers. When called with helpers, it returns only those helpers.

FuncMap panics for unknown helper identifiers because invalid helper identifiers are programming errors. Use FuncMapE when helper identifiers come from dynamic input.

func FuncMapE added in v0.0.2

func FuncMapE(helpers ...Helper) (template.FuncMap, error)

FuncMapE returns a template.FuncMap containing the selected helpers.

When called without arguments, FuncMapE returns all helpers. When called with helpers, it returns only those helpers.

FuncMapE returns an error for unknown helper identifiers.

func JSONValue

func JSONValue(value any) (string, error)

JSONValue renders value as a JSON literal.

This is useful when embedding dynamic strings, maps, slices, or structs in JSON templates.

"text": {{ .Subject | json }}

func LowerValue

func LowerValue(value any) string

LowerValue returns value as a lowercase string.

{{ .Status | lower }}

func OptionalValue

func OptionalValue(format string, values ...any) string

OptionalValue formats text only when all values are non-empty.

Empty follows the same rules as DefaultValue. Values are converted to strings and trimmed before formatting, so whitespace-only values are treated as empty.

The argument order supports direct and pipeline usage:

{{ optional "Status URL: %s" .App.StatusURL }}
{{ optional "%s: %s" .Label .Value }}
{{ .App.StatusURL | optional "Status URL: %s" }}

func TrimValue

func TrimValue(value any) string

TrimValue returns value as a string with surrounding whitespace removed.

{{ .Name | trim }}

func UpperValue

func UpperValue(value any) string

UpperValue returns value as an uppercase string.

{{ .Status | upper }}

func WhenValue

func WhenValue(condition, trueValue, falseValue any) any

WhenValue returns trueValue when condition is truthy, otherwise falseValue.

Truthiness follows template-style rules: nil, false, zero numbers, empty strings, empty arrays, empty maps, empty slices, empty channels, and nil pointers/interfaces are false. Other values are true.

The helper accepts any value type so it can be used with booleans, strings, numbers, slices, maps, and pointers.

{{ when .Resolved "Resolved at" "Notified at" }}
{{ when .Status "has status" "missing status" }}

func WithPrefixValue

func WithPrefixValue(prefix string, value any) string

WithPrefixValue returns value with prefix prepended when it is not already present.

The value and prefix are trimmed before comparison. The argument order supports both direct and pipeline usage:

{{ withPrefix "#" .CustomData.channel }}
{{ .CustomData.channel | withPrefix "#" }}

func WithSuffixValue

func WithSuffixValue(suffix string, value any) string

WithSuffixValue returns value with suffix appended when it is not already present.

The value and suffix are trimmed before comparison. The argument order supports both direct and pipeline usage:

{{ withSuffix "/" .Path }}
{{ .Path | withSuffix "/" }}

Types

type Helper

type Helper string

Helper identifies a template helper that can be registered in a FuncMap.

The constant name is exported for Go code. Its string value is the function name registered inside templates.

const (
	// JSON registers json, which renders a value as a JSON literal.
	JSON Helper = "json"

	// When registers when, which returns one of two values based on template truthiness.
	When Helper = "when"

	// Default registers default, which returns a fallback for empty values.
	Default Helper = "default"

	// Coalesce registers coalesce, which returns the first non-empty value.
	Coalesce Helper = "coalesce"

	// Optional registers optional, which formats text only when all values are non-empty.
	Optional Helper = "optional"

	// FormatTime registers formatTime, which formats a time value with a Go layout.
	FormatTime Helper = "formatTime"

	// Trim registers trim, which removes surrounding whitespace.
	Trim Helper = "trim"

	// Upper registers upper, which converts text to uppercase.
	Upper Helper = "upper"

	// Lower registers lower, which converts text to lowercase.
	Lower Helper = "lower"

	// WithPrefix registers withPrefix, which prepends a prefix when missing.
	WithPrefix Helper = "withPrefix"

	// WithSuffix registers withSuffix, which appends a suffix when missing.
	WithSuffix Helper = "withSuffix"

	// Duration registers duration, which renders a time.Duration or duration string.
	Duration Helper = "duration"
)

func All

func All() []Helper

All returns all built-in helpers in deterministic order.

Jump to

Keyboard shortcuts

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