Skip to content

Commit

Permalink
add option to skip template execution
Browse files Browse the repository at this point in the history
  • Loading branch information
nohajc committed Jan 27, 2024
1 parent 5257e26 commit 0f449a0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
15 changes: 13 additions & 2 deletions v2/i18n/localizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ type LocalizeConfig struct {

// Funcs is used to extend the Go template engine's built in functions
Funcs template.FuncMap

// NoTemplateExec is used to disable template execution.
// The localized string will be returned as is.
NoTemplateExec bool
}

type invalidPluralCountErr struct {
Expand Down Expand Up @@ -152,15 +156,15 @@ func (l *Localizer) LocalizeWithTag(lc *LocalizeConfig) (string, language.Tag, e
}

pluralForm := l.pluralForm(tag, operands)
msg, err2 := template.Execute(pluralForm, templateData, lc.Funcs)
msg, err2 := getOrExecute(template, pluralForm, templateData, lc)
if err2 != nil {
if err == nil {
err = err2
}

// Attempt to fallback to "Other" pluralization in case translations are incomplete.
if pluralForm != plural.Other {
msg2, err3 := template.Execute(plural.Other, templateData, lc.Funcs)
msg2, err3 := getOrExecute(template, plural.Other, templateData, lc)
if err3 == nil {
msg = msg2
}
Expand All @@ -169,6 +173,13 @@ func (l *Localizer) LocalizeWithTag(lc *LocalizeConfig) (string, language.Tag, e
return msg, tag, err
}

func getOrExecute(template *MessageTemplate, pluralForm plural.Form, data interface{}, lc *LocalizeConfig) (string, error) {
if lc.NoTemplateExec {
return template.Get(pluralForm)
}

Check warning on line 179 in v2/i18n/localizer.go

View check run for this annotation

Codecov / codecov/patch

v2/i18n/localizer.go#L178-L179

Added lines #L178 - L179 were not covered by tests
return template.Execute(pluralForm, data, lc.Funcs)
}

func (l *Localizer) getMessageTemplate(id string, defaultMessage *Message) (language.Tag, *MessageTemplate, error) {
_, i, _ := l.bundle.matcher.Match(l.tags...)
tag := l.bundle.tags[i]
Expand Down
12 changes: 12 additions & 0 deletions v2/i18n/message_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,15 @@ func (mt *MessageTemplate) Execute(pluralForm plural.Form, data interface{}, fun
}
return t.Execute(funcs, data)
}

// Get returns unprocessed template string for the plural form.
func (mt *MessageTemplate) Get(pluralForm plural.Form) (string, error) {
t := mt.PluralTemplates[pluralForm]
if t == nil {
return "", pluralFormNotFoundError{
pluralForm: pluralForm,
messageID: mt.Message.ID,
}
}
return t.Src, nil

Check warning on line 76 in v2/i18n/message_template.go

View check run for this annotation

Codecov / codecov/patch

v2/i18n/message_template.go#L68-L76

Added lines #L68 - L76 were not covered by tests
}

0 comments on commit 0f449a0

Please sign in to comment.