feat(i18n): add article phrase template helper
Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
parent
50c528ccf9
commit
eb45f9bfb1
2 changed files with 51 additions and 2 deletions
11
grammar.go
11
grammar.go
|
|
@ -555,6 +555,15 @@ func Quote(s string) string {
|
|||
return `"` + s + `"`
|
||||
}
|
||||
|
||||
// ArticlePhrase prefixes a noun phrase with the correct article.
|
||||
func ArticlePhrase(word string) string {
|
||||
article := Article(word)
|
||||
if article == "" || word == "" {
|
||||
return ""
|
||||
}
|
||||
return article + " " + word
|
||||
}
|
||||
|
||||
// TemplateFuncs returns the template.FuncMap with all grammar functions.
|
||||
func TemplateFuncs() template.FuncMap {
|
||||
return template.FuncMap{
|
||||
|
|
@ -565,7 +574,7 @@ func TemplateFuncs() template.FuncMap {
|
|||
"gerund": Gerund,
|
||||
"plural": Pluralize,
|
||||
"pluralForm": PluralForm,
|
||||
"article": Article,
|
||||
"article": ArticlePhrase,
|
||||
"quote": Quote,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
package i18n
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
func TestPastTense(t *testing.T) {
|
||||
// Ensure grammar data is loaded from embedded JSON
|
||||
|
|
@ -342,6 +346,26 @@ func TestQuote(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestArticlePhrase(t *testing.T) {
|
||||
tests := []struct {
|
||||
word string
|
||||
want string
|
||||
}{
|
||||
{"file", "a file"},
|
||||
{"error", "an error"},
|
||||
{"", ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.word, func(t *testing.T) {
|
||||
got := ArticlePhrase(tt.word)
|
||||
if got != tt.want {
|
||||
t.Errorf("ArticlePhrase(%q) = %q, want %q", tt.word, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabel(t *testing.T) {
|
||||
svc, err := New()
|
||||
if err != nil {
|
||||
|
|
@ -627,6 +651,22 @@ func TestTemplateFuncs(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestTemplateFuncs_Article(t *testing.T) {
|
||||
tmpl, err := template.New("").Funcs(TemplateFuncs()).Parse(`{{article "apple"}}`)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() failed: %v", err)
|
||||
}
|
||||
|
||||
var buf strings.Builder
|
||||
if err := tmpl.Execute(&buf, nil); err != nil {
|
||||
t.Fatalf("Execute() failed: %v", err)
|
||||
}
|
||||
|
||||
if got, want := buf.String(), "an apple"; got != want {
|
||||
t.Fatalf("template article = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Benchmarks ---
|
||||
|
||||
func BenchmarkPastTense_Irregular(b *testing.B) {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue