translator

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2025 License: MIT Imports: 11 Imported by: 0

README

go-translator

Overview

The Translator package is a Go module designed to facilitate easy and dynamic localization of applications. It provides a robust and flexible way to manage translations, including support for plural forms and customizable prefix handling for translation keys. This package utilizes the gotext library for managing PO files and integrates seamlessly with Go templates, making it an ideal solution for applications requiring multi-language support.

Features

  • Dynamic Language Support: Add new languages by parsing PO files.
  • Template Integration: Works with Go HTML templates, extracting translation keys directly from them.
  • Pluralization Support: Handles singular and plural forms for languages with complex plural rules.
  • Contextual Translations: Supports context-based translations for more accurate localization.
  • Prefix Handling: Customizable prefix handling in translation keys, allowing for organized and readable translation files.
  • Missing Translation Detection: Scans for and logs missing translations, simplifying the translation management process.

Installation

To install the Translator package, use the following go get command:

go get github.com/donseba/go-translator

Usage

Initializing the Translator

package main 

import "github.com/donseba/go-translator"

func main() {
    translationsDir := "path/to/translations"
    templateDir := "path/to/templates"

    tr := translator.NewTranslator(translationsDir, templateDir)
    tr.SetPrefixSeparator("__.") // Set the prefix separator if different from the default

    // load languages
    tr.AddLanguage("en_US")
    tr.AddLanguage("nl_NL")

    // check for missing translations and add them to the pot file
    err = app.Translation.CheckMissingTranslations("translations.pot")
    if err != nil {
        log.Fatal(err)
    }   
	
    // add template functions
    // this will add the tl, tn, ctl and ctn functions to the template
    var yourTemplateFunctions = make(template.FuncMap) 
    for k, v := range tr.FuncMap() {
        yourTemplateFunctions[k] = v
    }

Using the Translator in Templates

Use tl and ctl for translating singular texts and tn and ctn for plural forms.

<!-- Singular -->
<p>{{ tl .Loc "Hello, World!" }}</p>

<!-- Plural -->
<p>{{ tn .Loc "You have one message." "You have %d messages." 5, 5 }}</p>

Localizer interface

The Localizer interface is used to provide the translator with the current language. It is used to determine the correct translation for the given key.

	//Localizer interface contains the methods that are needed for the translator
Localizer interface {
   // GetLocale returns the locale of the localizer, ie. "en_US"
   GetLocale() string
}

Setting a language to use

tr.SetLanguage("en_US")
tr.SetLanguage("nl_NL")

Setting and possibly creating a New Language

To add or ensure a language file exists (and is loaded), use the EnsureLanguage method. This will create a new .po file with the correct header (including plural forms) if it does not exist, and then load it into the translator:

err := tr.EnsureLanguage("fr") // creates fr.po if missing, with correct header
if err != nil {
    log.Fatal(err)
}
  • The generated .po file will always include the recommended headers:

    • Content-Type: text/plain; charset=UTF-8
    • Content-Transfer-Encoding: 8bit
    • Plural-Forms (auto-filled from plural rules)
    • Language (set to the language code)
  • Calling EnsureLanguage multiple times is safe and will not overwrite existing files or translations.

Testing and Idempotency

  • The package includes tests to ensure that language files are created with the correct headers and that repeated calls to EnsureLanguage do not overwrite existing files.
  • Plural rules are generated from plurals.json and included in the codebase for accuracy and maintainability.

Updating Plural Rules

If you update plurals.json, regenerate the plural rules Go map by running:

go run tools/generate_templates.go

This will update generated_plural_templates.go with the latest plural forms and language codes.

Scanning for Missing Translations

To check for missing translations in your templates:

err := tr.CheckMissingTranslations("messages.pot")
if err != nil {
log.Fatal(err)
}

Customizing Prefix Separator

You can customize the prefix separator used in translation keys:

tr.SetPrefixSeparator("__CUSTOM__")

The default prefix separator is __.

Note/Disclaimer: While customizing the prefix separator is supported, it is generally recommended to use the CTL or CTN methods instead. These methods allow you to set translation context explicitly, which is more robust and flexible for handling similar keys in different contexts.

Removing Prefixes from Translations

The package automatically handles the removal of prefixes from translations at runtime:

translatedText := tr.Tl(localizer, "prefix__.your_translation_key") // output your_translation_key

TODO

  • add caching functionality of the loaded translated keys.
  • add more unit tests
  • live reload translations when the file changes
  • fallback language

Contributing

Contributions to the Translator package are welcome! Please submit a pull request or open an issue for any bugs, features, or improvements.

License

This package is licensed under MIT. Please see the LICENSE file for more details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrorLanguageNotFound      = fmt.Errorf("language not found")
	ErrorLanguageAlreadyExists = fmt.Errorf("language already exists")
)
View Source
var (
	TemplateExtension       = ".gohtml"
	DefaultPotFile          = "translations.pot"
	DefaultPoExtension      = ".po"
	DefaultNoTranslationTL  = "*%s*"
	DefaultNoTranslationTN  = "*%s/%s*"
	DefaultNoTranslationCTL = "*%s/%s*"
	DefaultNoTranslationCTN = "*%s/%s/%s*"
	DefaultSeparator        = "__."
)
View Source
var LanguageHeaderTemplates = map[string]TranslationFileHeader{}/* 216 elements not displayed */

Functions

func GenerateLanguageHeaderTemplatesFromJSON added in v1.2.0

func GenerateLanguageHeaderTemplatesFromJSON(jsonPath, goPath string) error

GenerateLanguageHeaderTemplatesFromJSON parses a plurals.json file and generates Go code for LanguageHeaderTemplates

func WritePOFile added in v1.2.0

func WritePOFile(path, language string) error

WritePOFile creates a PO file for a language with the default header if it does not exist

func WritePOTFile added in v1.2.0

func WritePOTFile(path string) error

WritePOTFile creates a POT file with the default header if it does not exist

Types

type Localizer

type Localizer interface {
	// GetLocale returns the locale of the localizer, ie. "en_US"
	GetLocale() string
}

Localizer interface contains the methods that are needed for the translator

type TranslationFileHeader added in v1.2.0

type TranslationFileHeader struct {
	ProjectID               string
	ReportMsgidBugsTo       string
	POTCreationDate         string
	PORevisionDate          string
	LastTranslator          string
	LanguageTeam            string
	Language                string
	MIMEVersion             string
	ContentType             string
	ContentTransferEncoding string
	PluralForms             string
}

func DefaultHeader added in v1.2.0

func DefaultHeader(language string) TranslationFileHeader

DefaultHeader returns a default header for a given language

func GetHeaderForLanguage added in v1.2.0

func GetHeaderForLanguage(language string) TranslationFileHeader

GetHeaderForLanguage returns a header template for a given language, falling back to DefaultHeader

func (TranslationFileHeader) HeaderString added in v1.2.0

func (h TranslationFileHeader) HeaderString() string

HeaderString returns the formatted header for a PO/POT file

type Translator

type Translator struct {
	// contains filtered or unexported fields
}

func NewTranslator

func NewTranslator(translationsDir, templateDir string) *Translator

func (*Translator) AddDetails

func (t *Translator) AddDetails(loc Localizer, key, value string) error

func (*Translator) AddLanguage

func (t *Translator) AddLanguage(lang string) error

AddLanguage adds a new language to the translator by loading its .po file. Deprecated: use SetLanguage instead

func (*Translator) CheckMissingTranslations

func (t *Translator) CheckMissingTranslations() error

CheckMissingTranslations scans template files for missing translations and logs them.

func (*Translator) Ctl

func (t *Translator) Ctl(loc Localizer, ctx, key string, args ...any) string

Ctl method for handling string translation with context

func (*Translator) Ctn

func (t *Translator) Ctn(loc Localizer, ctx, singular, plural string, n int) string

Ctn method for handling plurals with context

func (*Translator) Details

func (t *Translator) Details(loc Localizer) map[string][]string

Details return the header of the language file

func (*Translator) EnsureLanguage added in v1.2.0

func (t *Translator) EnsureLanguage(lang string) error

func (*Translator) FuncMap

func (t *Translator) FuncMap() template.FuncMap

func (*Translator) NewLanguage

func (t *Translator) NewLanguage(loc Localizer, headers ...map[string]string) error

func (*Translator) PotFile

func (t *Translator) PotFile() string

func (*Translator) PrefixSeparator

func (t *Translator) PrefixSeparator() string

func (*Translator) ScanFiles

func (t *Translator) ScanFiles(root string) error

func (*Translator) SetCTL

func (t *Translator) SetCTL(loc Localizer, key, ctx, value string) error

func (*Translator) SetCTN

func (t *Translator) SetCTN(loc Localizer, key, plural, ctx string, n int, value string) error

func (*Translator) SetDetails

func (t *Translator) SetDetails(loc Localizer, key, value string) error

func (*Translator) SetLanguage added in v1.2.0

func (t *Translator) SetLanguage(lang string) error

SetLanguage adds a new language to the translator by loading its .po file.

func (*Translator) SetPotFile

func (t *Translator) SetPotFile(potFile string)

func (*Translator) SetPrefixSeparator

func (t *Translator) SetPrefixSeparator(prefix string)

func (*Translator) SetRefs

func (t *Translator) SetRefs(loc Localizer, key string, refs []string) error

func (*Translator) SetTL

func (t *Translator) SetTL(loc Localizer, key string, value string) error

func (*Translator) SetTLN

func (t *Translator) SetTLN(loc Localizer, key, plural string, n int, value string) error

func (*Translator) SetTemplateDir

func (t *Translator) SetTemplateDir(templateDir string)

func (*Translator) SetTranslationsDir

func (t *Translator) SetTranslationsDir(translationsDir string)

func (*Translator) TemplateDir

func (t *Translator) TemplateDir() string

func (*Translator) Tl

func (t *Translator) Tl(loc Localizer, key string, args ...any) string

Tl translates a string based on the given language tag and key.

func (*Translator) Tn

func (t *Translator) Tn(loc Localizer, singular, plural string, n int) string

Tn method for handling plurals

func (*Translator) TranslationsDir

func (t *Translator) TranslationsDir() string

func (*Translator) Write

func (t *Translator) Write(loc Localizer) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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