国际化支持 Golang Web 应用程序 HTML 模板

i18n support for Golang Web application HTML templates

有人知道在 Golang Web 应用程序中本地化 HTML 模板吗?现在我正在使用 Gin 和 go-i18n,但如果它们可以本地化,我会使用其他框架。

如果可能,我想在 属性(或 JSON/yaml/toml,...)文件中为每种语言定义本地化消息:

label.password = パスワード # Password in Japanese 

并像 Thymeleaf 一样编写本地化 html:

<label th:text="#{label.password}"></label>

我选择使用 i18next 而不是 go-i18n,因为消息键可以嵌入 HTML 并替换为语言 JSON 文件。

Spreak 通过将定位器作为模板数据传递来支持模板本地化。 它还可以自动提取要翻译的字符串。

过程与go-i18n类似。 创建您的模板:

<label>{{.T.Get "Password"}}</label>

加载翻译:

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),
)

为请求创建本地化程序并将其作为模板数据传递。

func(c *gin.Context) {
    accept := c.GetHeader("Accept-Language")
    localizer := spreak.NewLocalizer(bundle, accept)
    
    c.HTML(http.StatusOK, "template.html", gin.H{
        "T": localizer,
    })
}

使用 xspreak 提取要翻译的字符串。

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"

创建了包含文件 base.pot 的目录 locale。 该文件是新翻译的模板,包含要翻译的 po 格式的字符串。文件的结构遵循以下结构:

#: ../template.html:8
#, go-template
msgid "Password"
msgstr ""

编辑最好使用PoEdit, but there are also many good alternatives之类的编辑器和网络平台。

用编辑器打开文件 base.pot,然后用翻译创建 .po 文件。 在您的示例中,这将是具有结构

的文件 locale/ja.po
#: ../template.html:8
#, go-template
msgid "Password"
msgstr "パスワード"

启动应用程序,将使用匹配的翻译。如果没有匹配的翻译,将显示原文。

我还使用 .i18n.Tr 作为模板中的翻译方法并使用多种语言创建了 a full example

注:我是spreak的作者