Skip to content

Commit

Permalink
Add plural function.
Browse files Browse the repository at this point in the history
Closes #12
  • Loading branch information
technosophos committed Jun 21, 2016
1 parent f2c3270 commit abe0997
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ parse, it returns the time unaltered. See `time.ParseDuration` for info on durat
- cat: Concatenate strings, separating them by spaces. `cat $a $b $c`.
- indent: Indent a string using space characters. `indent 4 "foo\nbar"` produces " foo\n bar"
- replace: Replace an old with a new in a string: `$name | replace " " "-"`
- plural: Choose singular or plural based on length: `len $fish | plural
"one anchovy" "many anchovies"`

### String Slice Functions:

Expand Down
9 changes: 9 additions & 0 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ String Functions
- cat: Concatenate strings, separating them by spaces. `cat $a $b $c`.
- indent: Indent a string using space characters. `indent 4 "foo\nbar"` produces " foo\n bar"
- replace: Replace an old with a new in a string: `$name | replace " " "-"`
- plural: Choose singular or plural based on length: `len $fish | plural "one anchovy" "many anchovies"`
String Slice Functions:
Expand Down Expand Up @@ -275,6 +276,7 @@ var genericMap = map[string]interface{}{
"cat": cat,
"indent": indent,
"replace": replace,
"plural": plural,

// Wrap Atoi to stop errors.
"atoi": func(a string) int { i, _ := strconv.Atoi(a); return i },
Expand Down Expand Up @@ -735,3 +737,10 @@ func indent(spaces int, v string) string {
func replace(old, new, src string) string {
return strings.Replace(src, old, new, -1)
}

func plural(one, many string, count int) string {
if count == 1 {
return one
}
return many
}
11 changes: 11 additions & 0 deletions functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,17 @@ func TestReplace(t *testing.T) {
}
}

func TestPlural(t *testing.T) {
tpl := `{{$num := len "two"}}{{$num}} {{$num | plural "1 char" "chars"}}`
if err := runt(tpl, "3 chars"); err != nil {
t.Error(err)
}
tpl = `{{len "t" | plural "cheese" "%d chars"}}`
if err := runt(tpl, "cheese"); err != nil {
t.Error(err)
}
}

func TestTuple(t *testing.T) {
tpl := `{{$t := tuple 1 "a" "foo"}}{{index $t 2}}{{index $t 0 }}{{index $t 1}}`
if err := runt(tpl, "foo1a"); err != nil {
Expand Down

0 comments on commit abe0997

Please sign in to comment.