英文:
Golang web app localization
问题
我有一个用Go语言编写的Web应用程序,我计划将其提供给多种语言的用户。我已经查看了多个可用的国际化(l18n)包,但有些问题不太清楚。
哪些包适合确定用户的语言环境并相应地加载网站?比如从浏览器偏好设置或位置信息获取用户的语言环境?
英文:
I have a web app written in golang, and I am planning to make it available in more than one language, I've taken a look at multiple available l18n packages but some things were not clear to me.
What packages would be ideal to determine the users locale and load the site accordingly? Like from browser preferences or location?
答案1
得分: 2
你可以使用https://github.com/nicksnyder/go-i18n/来进行翻译。
然后在你的项目中,你需要创建一个名为i18n/的文件夹,并使用以下函数:
import (
"fmt"
"io/ioutil"
"github.com/nicksnyder/go-i18n/i18n"
)
func loadI18nFiles() {
files, _ := ioutil.ReadDir("i18n")
exists := false
for _, file := range files {
if err := i18n.LoadTranslationFile(fmt.Sprintf("i18n/%s", file.Name())); err != nil {
log.Errorf("i18n: error loading file %s. err: %s", file.Name(), err)
} else {
log.Infof("i18n: lang file %s loaded", file.Name())
}
// 检查是否有默认语言
if file.Name() == fmt.Sprintf("%s.json", "en-US") {
exists = true
}
}
if !exists {
panic(fmt.Sprintf("Hey! You can't use a default language (%s) that doesn't exist in the i18n folder", props.DefaultLang))
}
}
然后导入该包并调用该函数:
T, _ := i18n.Tfunc("es-AR", "en-US")
fmt.Printf(T("key"))
i18n文件夹中的每个文件都是一个.json文件。
示例:
en-US.json
[
{
"id": "key",
"translation": "Hello World"
}
]
es-AR.json
[
{
"id": "key",
"translation": "Hola Mundo"
}
]
英文:
You can use https://github.com/nicksnyder/go-i18n/
Then in your project you have to create a folder called i18n/ and use a function like this:
import (
"fmt"
"io/ioutil"
"github.com/nicksnyder/go-i18n/i18n"
)
func loadI18nFiles() {
files, _ := ioutil.ReadDir("i18n")
exists := false
for _, file := range files {
if err := i18n.LoadTranslationFile(fmt.Sprintf("i18n/%s", file.Name())); err != nil {
log.Errorf("i18n: error loading file %s. err: %s", file.Name(), err)
} else {
log.Infof("i18n: lang file %s loaded", file.Name())
}
# Check if you have a default language
if file.Name() == fmt.Sprintf("%s.json", "en-US") {
exists = true
}
}
if !exists {
panic(fmt.Sprintf("Hey! You can't use a default language (%s) that doesn't exists on i18n folder", props.DefaultLang))
}
}
Then to use, import the package and call the function:
T, _ := i18n.Tfunc("es-AR", "en-US")
fmt.Printf(T("key"))
Each file inside i18n folder is a .json
Example:
en-US.json
[
{
"id": "key",
"translation": "Hello World"
}
]
es-AR.json
[
{
"id": "key",
"translation": "Hola Mundo"
}
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论