tinyi18n

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2023 License: GPL-2.0 Imports: 3 Imported by: 0

README

Tiny I18N

This is a tiny i18n library that takes texts from a CSV file, where each column represents another language.

Usage

1. Create a resource file like this:
key,            en,         de

button:save,    Save,       Speichern
button:close,   Close,      Schließen
button:abort,   Abort,      Abbrechen

header:options, Options,    Optionen

... and so on.

2. In your code, create and use a new Translator
package main

import (
    "fmt"
    "log"
    "os"

    i18n "codeberg.org/turysaz/tinyi18n"
)

func main() {

    texts, err := os.Open("my-resources.csv")
    if err != nil {
        log.Fatal(err)
    }
    defer texts.Close()

    translator, err := i18n.NewTranslator(texts)
    if err != nil {
        log.Fatal(err)
    }

    translator.Default = "de"

    fmt.Println(translator.GetDefault("button:save")) // "Speichern"
    fmt.Println(translator.Get("button:save", "en"))  // "Save"

    result, ok := translator.TryGet("foobar", "de") 
    if ok {
        fmt.Println(result)
    } else {
        fmt.Println("Text not found")
    }
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	CorruptResourcesError = errors.New("Resources file seems to be corrupt!")
	DuplicateLangError    = errors.New("Duplicate language definition!")
	DuplicateKeyError     = errors.New("Duplicate resource definition!")
)

Functions

This section is empty.

Types

type Translator

type Translator struct {
	// The default language key.
	// This key is used if no language is specified or if
	// the text for the chosen language is an empty string.
	Default string
	// contains filtered or unexported fields
}

func NewTranslator

func NewTranslator(resources io.Reader) (Translator, error)

func (*Translator) Get

func (t *Translator) Get(key, langKey string) string

Gets the translation for the specified language. If either the language or the key is not found, an empty string is returned. If the resulting text is an empty string, the default language is chosen instead. If the t.Default is "", the fallback mechanism is deactivated.

func (*Translator) GetDefault

func (t *Translator) GetDefault(key string) string

Gets the translation for the default language. If the default is set to empty, an empty string is returned.

func (*Translator) TryGet

func (t *Translator) TryGet(key, langKey string) (string, bool)

Gets the translation for the language. If the language or the key is not found, an empty string and a 'false' value is returned. If the text is an empty string, the default language is chosen instead. If the t.Default is "", the fallback mechanism is deactivated.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL