goeasyi18n

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2023 License: MIT Imports: 12 Imported by: 2

README

Tests status Latest releases Go package documentation

Go Easy i18n

Go Easy i18n

Effortlessly simple i18n for Go. Plurals, gender, and more made easy!

  • 🚀 Making Internationalization a Breeze in Go!
  • 🔥 Simple yet flexible i18n library for Go developers.
  • 📦 Supports pluralization, gender, and more with zero hassle!
  • 👩‍💻 Perfect for projects that need quick and easy localization.
  • 🚫 No weird or complicated usage. Just simple and easy to use.
  • 🌍 Go global, the easy way!

Installation 📦

go get github.com/eduardolat/goeasyi18n

QuickStart 🚀

package main

import (
	"fmt"

	"github.com/eduardolat/goeasyi18n"
)

func main() {
	// 1. Create a new i18n instance
	// You can skip the goeasyi18n.Config{} entirely if you are
	// ok with the default values.
	i18n := goeasyi18n.NewI18n(goeasyi18n.Config{
		FallbackLanguageName: "en", // It's optional, the default value is "en"
		DisableConsistencyCheck: false, // It's optional, the default value is false
	})

	// 2. Add languages and its translations (can be loaded from a JSON/YAML file)
	// using bytes, strings, files or fs.FS (embed.FS)
	i18n.AddLanguage("en", goeasyi18n.TranslateStrings{
		{
			Key:     "hello_message",
			Default: "Hello, welcome to Go Easy i18n!",
		},
	})

	i18n.AddLanguage("es", goeasyi18n.TranslateStrings{
		{
			Key:     "hello_message",
			Default: "¡Hola, bienvenido a Go Easy i18n!",
		},
	})

	// 3. You are done! 🎉 Just get that translations!
	t1 := i18n.Translate("en", "hello_message", goeasyi18n.Options{})
	t2 := i18n.Translate("es", "hello_message") // You can skip the options if you don't need them

	fmt.Println(t1)
	fmt.Println(t2)

	/*
		Prints:
		Hello, welcome to Go Easy i18n!
		¡Hola, bienvenido a Go Easy i18n!
	*/
}

Learn Go (Easy i18n) by Examples 📚

This is the complete list of examples that covers all the features of Go Easy i18n from the most basic to the most advanced usage. If you want to be a pro, you should read them all!

Combining these features you can go as simple or complex as you want.

Tip: Read it in order, from top to bottom.

You are done! 🎉🎉🎉

If you find this library useful, please 🙏 give it a star ⭐️ on GitHub and share it with your friends.

Want to Contribute? 🌟

We're thrilled you're considering contributing to Go Easy i18n! Your help is invaluable. Whether it's through code improvements, bug fixes, or enhancing documentation, every contribution counts. If you're unsure where to start or have any questions, feel free to open an issue. For detailed guidelines on making contributions, please read our CONTRIBUTING.md file.

FAQ ❓

Why should I use this library?

This library makes internationalization in Go extremely simple and flexible. It supports pluralization, gender, and more, all without any hassle. It's designed to be easy to use, so you can go global without breaking a sweat.

Am i enforced to build my project in a specific way?

No, this library is designed to be as flexible as possible. You can integrate it into your existing project structure without any major changes.

How can i name my languages?

You have complete freedom to name your languages as you see fit. For example, you could use URLs like example.com/en or example.com/en-US to identify languages. However, you're responsible for extracting this segment from the URL and using it in your application.

How can i name my translation files?

You can name your translation files however you like. The library is agnostic to file naming conventions.

From where should i load my translations?

Translations can be loaded from any JSON or YAML file. You have the flexibility to create your own database or any other mechanism that generates these files, and then load them into the library.

Custom Pluralization: Why is it useful?

Imagine you're building an app that shows the number of unread messages. In English, you'd say "1 unread message" and "2 unread messages" - note the "s" at the end. But what about languages where plural rules aren't so simple?

With custom pluralization, you can easily handle these cases without writing complex if-else statements. Just define your plural rules once, and let the library do the heavy lifting!

This makes your code cleaner and your app more linguistically accurate. Win-win!

Gender Handling: Why is it useful?

Let's say your app has a feature that says, "John liked your post" or "Emily liked your post." In some languages, the verb "liked" might change based on the gender of the person who liked the post.

Example:

  • English: "He liked your post" vs "She liked your post"
  • Spanish: "A él le gustó tu publicación" vs "A ella le gustó tu publicación"

With gender-specific translations, you can easily adapt the sentence structure to fit the gender, making your app more linguistically accurate and inclusive.

No need for messy if-else statements to handle gender variations. Just set it up once, and the library takes care of the rest!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultPluralizationFunc

func DefaultPluralizationFunc(count int) string

DefaultPluralizationFunc is the function that is used if no custom pluralization function is set for the language

func ExecuteTemplate

func ExecuteTemplate(templateStr string, data any) string

Types

type Config

type Config struct {
	// Default: "en"
	FallbackLanguageName string
	// Default: false
	DisableConsistencyCheck bool
}

Config is used to configure the i18n object

type Data

type Data map[string]any

type I18n

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

func NewI18n

func NewI18n(config ...Config) *I18n

NewI18n creates and returns a new i18n object

func (*I18n) AddLanguage

func (t *I18n) AddLanguage(
	languageName string,
	translateStrings TranslateStrings,
) []string

AddLanguage adds a language to the i18n object with its translations and after that it check if the language is consistent with the other languages (can be disabled with the config)

It returns a slice of errors as strings if the language is not consistent with the other languages and the consistency check is enabled

func (*I18n) CheckLanguageConsistency added in v1.3.0

func (t *I18n) CheckLanguageConsistency(
	langNameToCheck string,
) (bool, []string)

CheckLanguageConsistency checks if a language is consistent with the other languages, it checks if the translations keys are the same in all languages

func (*I18n) HasLanguage

func (t *I18n) HasLanguage(languageName string) bool

HasLanguage checks if a language is available (if is loaded)

func (*I18n) NewLangTranslateFunc added in v1.2.0

func (t *I18n) NewLangTranslateFunc(
	languageName string,
) func(
	translateKey string,
	options ...Options,
) string

NewLangTranslateFunc creates a function to translate a string in a specific language without the need to pass the language name every time.

func (*I18n) NewTemplatingTranslateFunc

func (t *I18n) NewTemplatingTranslateFunc() func(args ...interface{}) string

NewTemplatingTranslateFunc creates a function that can be used in text/template and html/template. Just pass the created function to template.FuncMap.

Example:

tempTemplate := template.New("main").Funcs(

	template.FuncMap{
		// 👇 "Translate" could be just "T" (for simplicity) or any other name you want.
		"Translate": i18n.NewTemplatingTranslateFunc(),
	},

)

Then you can use it in your template like this:

{{ Translate "lang" "en" "key" "hello_emails" "gender" "nonbinary" "count" "100" "SomeData" "Anything" }}

The format is key-value based and the order doesn't matter. This is the format:

{{ Translate "key1" "value1" "key2" "value2" ... }}

Arguments:

- "lang" "en": Language code (e.g., "en", "es").

- "key" "hello_emails": Translation key.

- "gender" "nonbinary": Gender for the translation (optional).

- "count" "100": Count for pluralization (optional).

- Additional key-value pairs will be added to the Data map.

Arguments are passed in pairs. The first item in each pair is the key, and the second is the value.

Key-Value Explanation:

- Each argument is processed as a pair: the first string is considered the key and the second string is the value.

- For example, in "lang" "en", "lang" is the key and "en" is the value.

As you can imagine, "lang", "key", "gender", and "count" are reserved keys. You can use any other key you want to pass data to translation.

Note: All arguments are strings. The function will attempt to convert "count" to an integer.

func (*I18n) SetPluralizationFunc

func (t *I18n) SetPluralizationFunc(languageName string, fn PluralizationFunc)

SetPluralizationFunc sets the pluralization function for a language

func (*I18n) T

func (t *I18n) T(
	languageName string,
	translateKey string,
	options ...Options,
) string

T is a shortcut for Translate

func (*I18n) Translate

func (t *I18n) Translate(
	languageName string,
	translateKey string,
	options ...Options,
) string

Translate translates a string in a specific language using a key and additional optional options

type Options

type Options struct {
	Data   any
	Count  *int
	Gender *string // male, female, nonbinary, non-binary (case insensitive)
}

Options are the additional options for the Translate function

type PluralizationFunc

type PluralizationFunc func(count int) string

type TranslateString

type TranslateString struct {
	Key     string
	Default string

	// For pluralization
	Zero string // Optional
	One  string // Optional
	Two  string // Optional
	Few  string // Optional
	Many string // Optional

	// For genders
	Male      string // Optional
	Female    string // Optional
	NonBinary string // Optional

	// For pluralization with male gender
	ZeroMale string // Optional
	OneMale  string // Optional
	TwoMale  string // Optional
	FewMale  string // Optional
	ManyMale string // Optional

	// For pluralization with female gender
	ZeroFemale string // Optional
	OneFemale  string // Optional
	TwoFemale  string // Optional
	FewFemale  string // Optional
	ManyFemale string // Optional

	// For pluralization with non binary gender
	ZeroNonBinary string // Optional
	OneNonBinary  string // Optional
	TwoNonBinary  string // Optional
	FewNonBinary  string // Optional
	ManyNonBinary string // Optional
}

type TranslateStrings

type TranslateStrings []TranslateString

func LoadFromJsonBytes added in v1.3.0

func LoadFromJsonBytes(
	jsonBytes []byte,
) (TranslateStrings, error)

LoadFromJsonBytes loads a list of TranslateString from the provided JSON bytes.

func LoadFromJsonFS added in v1.3.0

func LoadFromJsonFS(
	fileSystem fs.FS,
	filesOrGlobs ...string,
) (TranslateStrings, error)

LoadFromJsonFS loads a list of TranslateString from one or multiple JSON files located within a provided filesystem (fs.FS), allowing glob patterns like "path/to/files/*.json".

func LoadFromJsonFiles added in v1.3.0

func LoadFromJsonFiles(
	filesOrGlobs ...string,
) (TranslateStrings, error)

LoadFromJsonFiles loads a list of TranslateString from one or multiple JSON files, allowing glob patterns like "path/to/files/*.json".

func LoadFromJsonString added in v1.3.0

func LoadFromJsonString(
	jsonString string,
) (TranslateStrings, error)

LoadFromJsonString loads a list of TranslateString from the provided JSON string.

func LoadFromYamlBytes added in v1.3.0

func LoadFromYamlBytes(
	yamlBytes []byte,
) (TranslateStrings, error)

LoadFromYamlBytes loads a list of TranslateString from the provided YAML bytes.

func LoadFromYamlFS added in v1.3.0

func LoadFromYamlFS(
	fileSystem fs.FS,
	filesOrGlobs ...string,
) (TranslateStrings, error)

LoadFromYamlFS loads a list of TranslateString from one or multiple YAML files located within a provided filesystem (fs.FS), allowing glob patterns like "path/to/files/*.yaml".

func LoadFromYamlFiles added in v1.3.0

func LoadFromYamlFiles(
	filesOrGlobs ...string,
) (TranslateStrings, error)

LoadFromYamlFiles loads a list of TranslateString from one or multiple YAML files, allowing glob patterns like "path/to/files/*.yaml".

func LoadFromYamlString added in v1.3.0

func LoadFromYamlString(
	yamlString string,
) (TranslateStrings, error)

LoadFromYamlString loads a list of TranslateString from the provided YAML string.

Jump to

Keyboard shortcuts

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