Skip to content
This repository has been archived by the owner on Jan 28, 2025. It is now read-only.

Commit

Permalink
Merge pull request #10 from mailgun/cclark/dev
Browse files Browse the repository at this point in the history
PIP-1385: add pluralize helper
  • Loading branch information
Takumi2008 authored Aug 24, 2021
2 parents c3a4305 + 588d69a commit cd18a09
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
8 changes: 8 additions & 0 deletions helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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) {
Expand Down
43 changes: 43 additions & 0 deletions helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
`<option value="test" {{#equal value "test"}}selected{{/equal}}>Test</option>`,
Expand Down

0 comments on commit cd18a09

Please sign in to comment.