108 lines
2.4 KiB
Markdown
108 lines
2.4 KiB
Markdown
# Translation
|
|
|
|
A package that handles translations using JSON files.
|
|
|
|
## Installation
|
|
|
|
To include the translation package in your Go project, run the following command:
|
|
|
|
```bash
|
|
go get git.apihub24.de/admin/translation
|
|
```
|
|
|
|
## Usage
|
|
|
|
You must have a folder containing JSON files. Each file should hold an object with key-value pairs where the value is a string.
|
|
|
|
- translations/de.json
|
|
|
|
```json
|
|
{
|
|
"SOME_KEY": "ein Wert"
|
|
}
|
|
```
|
|
|
|
- translations/en.json
|
|
|
|
```json
|
|
{
|
|
"SOME_KEY": "a Value"
|
|
}
|
|
```
|
|
|
|
Next, you can create a Go file that embeds these JSON files using fs.Files.
|
|
|
|
- translations/files.go
|
|
|
|
```go
|
|
package translations
|
|
|
|
import "embed"
|
|
|
|
//go:embed *.json
|
|
var Files embed.FS
|
|
```
|
|
|
|
Now, use the translation package to set up and retrieve translations on demand:
|
|
|
|
```go
|
|
package main
|
|
|
|
import (
|
|
"git.apihub24.de/admin/translation"
|
|
translations "{link to your translations folder}"
|
|
)
|
|
|
|
func main() {
|
|
// give the Init Function the translations fs.Files
|
|
translation.Init(translations.Files)
|
|
// Optional you can change the Fallback Language
|
|
translation.SetDefaultCulture("de")
|
|
|
|
// get the Translation Values
|
|
translation.Get("SOME_KEY", "de")
|
|
}
|
|
```
|
|
|
|
### Error Handling & Fallback Behavior
|
|
|
|
- If a translation key is not found for the requested language, the package will attempt to retrieve the translation from the default culture (set via SetDefaultCulture).
|
|
- If the key is not found even in the default culture, or if the specified language file does not exist, translation.Get will return the following string 'no value for key {key} found in source {culture}'. This helps in identifying missing translations directly in your application.
|
|
|
|
## Features
|
|
|
|
### Translation Keys
|
|
|
|
You can use any translation key you want. The only thing to keep in mind is that your translation files must have the translation key as part of their filename.
|
|
|
|
For example, if you want to split your translation files into modules, you can name them like this:
|
|
|
|
- translations/global_de.json
|
|
- translations/global_en.json
|
|
- translations/mod1_de.json
|
|
- translations/mod1_en.json
|
|
- translations/mod2_de.json
|
|
- translations/mod2_en.json
|
|
|
|
And the translation call would look like this:
|
|
|
|
```go
|
|
translation.Get("SOME_KEY", "global_de")
|
|
```
|
|
|
|
### Parameters
|
|
|
|
You can use placeholders to create dynamic translation values.
|
|
|
|
For example:
|
|
|
|
```json
|
|
{
|
|
"DYNAMIC": "Preis: %[1]s %[1]s"
|
|
}
|
|
```
|
|
|
|
```go
|
|
translation.Get("DYNAMIC", "de", "12,50", "€")
|
|
```
|