Reputation: 5122
Does anyone has a good idea to localize HTML templates in Golang Web application? Now I'm using Gin and go-i18n, but I will use other frameworks if they can localize.
If possible, I want to define the localized messages in property (or JSON/yaml/toml,...) files for each language:
label.password = パスワード # Password in Japanese
and write localized html like Thymeleaf:
<label th:text="#{label.password}"></label>
Upvotes: 4
Views: 3132
Reputation: 1
Spreak supports template localization by passing a localizer as template data. It can also automatically extract the strings to be translated.
The process is similar to that of go-i18n. Create your templates:
<label>{{.T.Get "Password"}}</label>
Load the translations:
bundle, err := spreak.NewBundle(
spreak.WithSourceLanguage(language.English),
// Set the path from which the translations should be loaded
spreak.WithDomainPath(spreak.NoDomain, "locale"),
// Specify the languages you want to load
spreak.WithLanguage(language.Japanese, language.German),
)
Create a localizer for a request and pass it as template data.
func(c *gin.Context) {
accept := c.GetHeader("Accept-Language")
localizer := spreak.NewLocalizer(bundle, accept)
c.HTML(http.StatusOK, "template.html", gin.H{
"T": localizer,
})
}
Use xspreak to extract the strings to be translated.
go install github.com/vorlif/xspreak@latest
xspreak -D path/to/code -o path/to/code/locale/base.pot --template-prefix "T" -t "templates/*.html"
A directory locale
with a file base.pot
is created.
The file is the template for new translations and contains the strings to be translated in po
-format. The structure of the file follows the structure:
#: ../template.html:8
#, go-template
msgid "Password"
msgstr ""
For editing, it is best to use an editor like PoEdit, but there are also many good alternatives and online platforms.
Open the file base.pot
with an editor and create your .po
files with the translations.
In your example, this would be the file locale/ja.po
with the structure
#: ../template.html:8
#, go-template
msgid "Password"
msgstr "パスワード"
Start the application and the matching translations will be used. The original text will be displayed if there are no matching translations.
I also created a full example using .i18n.Tr
as translation method in the templates and using multiple languages.
Note: I am the author of spreak.
Upvotes: 0
Reputation: 5122
I chose to use i18next instead of go-i18n because the message keys can be embedded in HTML and replaced with language JSON files.
Upvotes: 2