goyai

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2022 License: MIT Imports: 16 Imported by: 1

README

goyai

Go Report Card PkgGoDev Actions Status codecov Release

Yet Another I18n package for Go (Golang).

Feature overview

  • Support localized text messages, with plural forms.
  • Support template string with named variables following text/template syntax.
  • Support language files in JSON and YAML formats.
  • Can be used in/integrated with html/template (since v0.2.0).

Installation

go get github.com/btnguyen2k/goyai

Usage & Documentation

PkgGoDev

Language file format

goyai supports language files in JSON and YAML (1.2) formats. Here is an example of language file in YAML:

---
en:
  _name: English
  hello: Hello, world!
  hello_param: Hello buddy {{.name}}
  remaining_tasks:
    zero: Congratulation {{.who}}! You are free now.
    one: There is 1 task left.
    two: There are 2 tasks left.
    few: There are a few tasks left.
    many: There are many tasks left.
    other: Hmmm!

vi:
  _name: Tiếng Việt
  hello: Xin chào
  hello_param: Chào bạn {{.name}}
  remaining_tasks:
    zero: Chúc mừng {{.who}}! Bạn đã hoàn thành công việc.
    one: Vẫn còn 1 công việc nữa cần hoàn thành.
    two: Còn 1 công việc nữa cần hoàn thành.
    few: Vẫn còn vài công việc nữa cần hoàn thành.
    many: Còn quá trời việc chưa hoàn thành.
    other: Á chà!

Multi-document YAML is currently not supported! Only the first document in multi-document YAML file is loaded.

Load language files and build an I18n instance to use

import "github.com/btnguyen2k/goyai"

i18n, err := BuildI18n(goyai.I18nOptions{ConfigFileOrDir: "all_in_one.yaml", goyai.I18nFileFormat: goyai.Yaml, DefaultLocale: "en"})
if err != nil {
    panic(err)
}

Supported language file formats are goyai.Json and goyai.Yaml. File format is automatically detected if goyai.Auto is specified.

Language messages can spread multiple files in a directory and be loaded in one go:

i18n, err := BuildI18n(goyai.I18nOptions{ConfigFileOrDir: "./languages/", I18nFileFormat: goyai.Auto, DefaultLocale: "en"})

Localize messages via I18n instance

// output "Xin chào"
fmt.Println(i18n.Localize("vi", "hello"))

// locale "nf" does not exist, fall back to default locale "en"
// output "Hello, world!"
fmt.Println(i18n.Localize("nf", "hello"))

// Pass template data, output "Hello buddy Thanh"
fmt.Println(i18n.Localize("en", "hello_param", goyai.LocalizeConfig{TemplateData: map[string]interface{}{"name": "Thanh"}}))

// Plural form, output "There is 1 task left."
fmt.Println(i18n.Localize("en", "remaining_tasks", goyai.LocalizeConfig{PluralCount: 1}))

// Plural form, output "There are 2 tasks left."
fmt.Println(i18n.Localize("en", "remaining_tasks", goyai.LocalizeConfig{PluralCount: 2}))

// Plural form, these commands output "Hmmm!"
fmt.Println(i18n.Localize("en", "remaining_tasks")) // no PluralCount specified, plural form "other" is used
fmt.Println(i18n.Localize("en", "remaining_tasks", goyai.LocalizeConfig{PluralCount: -1})) // plural form "other" is used

// Plural form, output "There are many tasks left."
fmt.Println(i18n.Localize("en", "remaining_tasks", goyai.LocalizeConfig{PluralCount: 3}))

// Plural form & pass template data, output "Congratulation btnguyen2k! You are free now."
fmt.Println(i18n.Localize("en", "remaining_tasks", goyai.LocalizeConfig{PluralCount: 0, TemplateData: map[string]interface{}{"name": "btnguyen2k"}}))

Plural forms

A localized message can have several plural forms, specified by zero, one, two, few, many and other attributes in the language file. Plural form of a message is picked up based on the following rules:

  • if PluralCount is negative number, nil or not cast-able to integer, the other form is chosen.
  • if PluralCount=0, the zero form is chosen.
  • if PluralCount=1, one of one/few/other forms is chosen, priority is from left to right (e.g. one form has the highest priority, if absent, the next one is checked)
  • if PluralCount=2, one of two/many/other forms is chosen, priority is from left to right (e.g. two form has the highest priority, if absent, the next one is checked)
  • if PluralCount>2, one of many/other forms is chosen, priority is from left to right (e.g. many form has the highest priority, if absent, the next one is checked)

If a message is defined by a simple string (e.g. hello: Hello, world!), the string is the content of the message's plural form other and all other plural forms are empty.

Used in html/template template

html/template support requires v0.2.0 or higher.

Assuming the I18n instance is pass to a html/template template as a model named i18n. Then

  • Template The message: {{.i18n.Localize "en" "hello"}} will be rendered as The message: Hello, world!.
  • Template The message: {{.i18n.Localize "en" "hello_param" "Thanh"}} will be rendered as The message: Hello buddy Thanh.

Plural form is current not supported if used in html/template template.

Contributing

Use Github issues for bug reports and feature requests.

Contribute by Pull Request:

  1. Fork goyai on github (https://help.github.com/articles/fork-a-repo/)
  2. Create a topic branch (git checkout -b my_branch)
  3. Implement your change
  4. Push to your branch (git push origin my_branch)
  5. Post a pull request on github (https://help.github.com/articles/creating-a-pull-request/)

License

MIT - see LICENSE.md.

Documentation

Overview

Package goyai provides a simple interface to support i18n for Go applications.

Index

Constants

View Source
const (
	// Version of goyai package
	Version = "0.2.0"
)

Variables

View Source
var (
	// ErrInvalidFileFormat indicates that the specified language file format is not supported.
	ErrInvalidFileFormat = errors.New("language file format is invalid or not supported")
)

Functions

This section is empty.

Types

type Goi18n

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

Goi18n is the default I18n implementation from goyai.

func (*Goi18n) AvailableLocales

func (i *Goi18n) AvailableLocales() []LocaleInfo

AvailableLocales implements I18n.AvailableLocales.

func (*Goi18n) Localise added in v0.2.0

func (i *Goi18n) Localise(locale, msgId string, params ...interface{}) string

Localise implements I18n.Localise

func (*Goi18n) Localize

func (i *Goi18n) Localize(locale, msgId string, params ...interface{}) string

Localize implements I18n.Localize

type I18n

type I18n interface {
	// Localize returns a localized message. Params are optional, a param can be either a string, number, boolean or a LocalizeConfig instance.
	// Note: params can be mixed of strings, numbers and booleans but not LocalizeConfig instances. If there is one or more
	// LocalizeConfig instances are supplied, only the first one is used; all other params are ignored (including
	// strings/numbers/booleans and other LocalizeConfig instances).
	Localize(locale, msgId string, params ...interface{}) string

	// Localise is alias of Localize.
	//
	// Available since v0.2.0
	Localise(locale, msgId string, params ...interface{}) string

	// AvailableLocales returns all defined locale configurations.
	AvailableLocales() []LocaleInfo
}

I18n is the main interface of goyai package, offering APIs to render a message.

func BuildI18n

func BuildI18n(opts I18nOptions) (I18n, error)

BuildI18n builds an I18n instance from message file(s) and returns it.

func NullI18n

func NullI18n() I18n

NullI18n returns a "null" I18n instance.

type I18nFileFormat

type I18nFileFormat int

I18nFileFormat defines list of supported i18n configuration file formats.

const (
	// Auto hints that the file format should be automatically detected.
	Auto I18nFileFormat = iota

	// Json hints that the file is JSON-encoded.
	Json

	// Yaml hints that the file is YAML-encoded.
	Yaml
)

type I18nOptions

type I18nOptions struct {
	// ConfigFileOrDir points to the configuration file or the directory where configuration files are located.
	ConfigFileOrDir string

	// DefaultLocale is the default locale to be used when non specified.
	DefaultLocale string

	// I18nFileFormat hints the format of configuration files.
	I18nFileFormat I18nFileFormat
}

I18nOptions specifies options to build new I18n instances.

type LocaleInfo

type LocaleInfo struct {
	Id          string
	DisplayName string
}

LocaleInfo captures info of a locale package.

type LocalizeConfig

type LocalizeConfig struct {
	// TemplateData is used to transform the message's template.
	TemplateData map[string]interface{}

	// PluralCount determines which plural form of the message is used. PluralCount must be an integer or nil.
	// See Message for more information.
	//
	// Rule for picking plural form:
	// - if PluralCount is negative number, nil or not cast-able to integer, the "other" form is chosen.
	// - if PluralCount = 0, the "zero" form is chosen.
	// - if PluralCount = 1, one of "one"/"few"/"other" forms is chosen, priority is from left to right (e.g. "one" form has the highest priority, if absent, the next one is checked)
	// - if PluralCount = 2, one of "two"/"many"/"other" forms is chosen, priority is from left to right (e.g. "two" form has the highest priority, if absent, the next one is checked)
	// - if PluralCount > 2, one of "many"/"other" forms is chosen, priority is from left to right (e.g. "many" form has the highest priority, if absent, the next one is checked)
	PluralCount interface{}

	// DefaultMessage holds the default message where there is no localized one.
	DefaultMessage string
}

LocalizeConfig configures how a message should be localised, used by function I18n.Localize.

type Message

type Message struct {
	// Id is the message's unique identity.
	Id string

	// Description provides additional information about the message.
	Description string

	// Zero is the message's content for the CLDR plural form "zero".
	Zero string

	// One is the message's content for the CLDR plural form "one".
	One string

	// Two is the message's content for the CLDR plural form "two".
	Two string

	// Few is the message's content for the CLDR plural form "few".
	Few string

	// Many is the message's content for the CLDR plural form "many".
	Many string

	// Other is the message's content for the CLDR plural form "other".
	Other string
}

Message represents a message that can be localized.

func ParseMessage

func ParseMessage(id string, data interface{}) (*Message, error)

ParseMessage parses data and returns a new Message instance.

data must be either a string, or a map[string]string. If data is a string, the Message is constructed with data is the value of the plural form "other".

Jump to

Keyboard shortcuts

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