Skip to content

Commit

Permalink
feat: Transform newlines in HTML translations (#4272)
Browse files Browse the repository at this point in the history
Some localization strings include new line characters (i.e. `\n`) to
control the flow of text while avoiding the multiplication of strings
to manage (i.e. one per line).

However, these characters were not transformed into `<br />` tags by
the HTML translator thus effectively losing the expected text flow in
the resulting HTML.
  • Loading branch information
taratatach authored Dec 22, 2023
2 parents 5666dba + 2cebe82 commit 0a9731d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
2 changes: 2 additions & 0 deletions pkg/i18n/i18n.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func Translator(locale, contextName string) func(key string, vars ...interface{}
}

var boldRegexp = regexp.MustCompile(`\*\*(.*?)\*\*`)
var newlineRegexp = regexp.MustCompile(`(\n)`)

// TranslatorHTML returns a translation function of the locale specified, which
// allow simple markup like **bold**.
Expand All @@ -42,6 +43,7 @@ func TranslatorHTML(locale, contextName string) func(key string, vars ...interfa
translated := Translate(key, locale, contextName, vars...)
escaped := template.HTMLEscapeString(translated)
replaced := boldRegexp.ReplaceAllString(escaped, "<strong>$1</strong>")
replaced = newlineRegexp.ReplaceAllString(replaced, "<br />")
return template.HTML(replaced)
}
}
Expand Down
49 changes: 49 additions & 0 deletions pkg/i18n/i18n_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package i18n

import (
"html/template"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -46,3 +47,51 @@ msgstr "contexte foo"
s = Translate("context", "fr", "bar")
assert.Equal(t, "contexte", s)
}

func TestTranslatorHTML(t *testing.T) {
contextName := "foo"

LoadLocale("fr", "", []byte(`
msgid "english"
msgstr "french"
msgid "hello %s"
msgstr "bonjour **%s**"
msgid "context"
msgstr "contexte"
`))

LoadLocale("fr", contextName, []byte(`
msgid "english"
msgstr "french"
msgid "hello %s"
msgstr "bonjour **%s**"
msgid "context"
msgstr ""
"contexte\n"
"foo"
`))

frHTML := TranslatorHTML("fr", contextName)

h := frHTML("english")
assert.Equal(t, template.HTML("french"), h)
h = frHTML("hello %s", "toto")
assert.Equal(t, template.HTML("bonjour <strong>toto</strong>"), h)

enHTML := TranslatorHTML("en", contextName)
h = enHTML("english")
assert.Equal(t, template.HTML("english"), h)
h = enHTML("hello %s", "toto")
assert.Equal(t, template.HTML("hello toto"), h)

h = frHTML("context")
assert.Equal(t, template.HTML("contexte<br />foo"), h)

barHTML := TranslatorHTML("fr", "bar")
h = barHTML("context")
assert.Equal(t, template.HTML("contexte"), h)
}

0 comments on commit 0a9731d

Please sign in to comment.