diff --git a/helper.go b/helper.go index 820c34b..b362582 100644 --- a/helper.go +++ b/helper.go @@ -44,6 +44,7 @@ func init() { RegisterHelper("ifLt", ifLtHelper) RegisterHelper("ifEq", ifEqHelper) RegisterHelper("ifMatchesRegexStr", ifMatchesRegexStr) + RegisterHelper("pluralize", pluralizeHelper) // Register builtin param helpers. RegisterParamHelper("length", lengthParamHelper) @@ -395,6 +396,13 @@ func ifMatchesRegexStr(a, b interface{}, options *Options) interface{} { return options.Inverse() } +func pluralizeHelper(count, plural, singular interface{}) interface{} { + if c, err := floatValue(count); err != nil || c <= 1 { + return singular + } + return plural +} + // #unless block helper func unlessHelper(conditional interface{}, options *Options) interface{} { if options.isIncludableZero() || IsTrue(conditional) { diff --git a/helper_test.go b/helper_test.go index 66a8b59..82f6298 100644 --- a/helper_test.go +++ b/helper_test.go @@ -527,6 +527,49 @@ var helperTests = []Test{ nil, nil, nil, `Length is not equal to 4`, }, + { + "pluralize result plural", + `{{pluralize error_count "errors" "error"}}`, + map[string]interface{}{"error_count": 3}, + nil, nil, nil, + `errors`, + }, + { + "pluralize result singular", + `{{pluralize error_count "errors" "error"}}`, + map[string]interface{}{"error_count": 1}, + nil, nil, nil, + `error`, + }, + { + "pluralize with vars result plural", + `{{pluralize error.count error.plural error.singular}}`, + map[string]interface{}{"error": map[string]interface{}{ + "count": 3, + "plural": "errors", + "singular": "error", + }}, + nil, nil, nil, + `errors`, + }, + { + "pluralize with vars result singular", + `{{pluralize error.count error.plural error.singular}}`, + map[string]interface{}{"error": map[string]interface{}{ + "count": 1, + "plural": "errors", + "singular": "error", + }}, + nil, nil, nil, + `error`, + }, + { + "pluralize count non-number", + `{{pluralize error_count "errors" "error"}}`, + map[string]interface{}{"error_count": "three"}, + nil, nil, nil, + `error`, + }, { "#equal helper inside HTML tag", ``,