• Stars
    star
    105
  • Rank 328,196 (Top 7 %)
  • Language
    Go
  • License
    MIT License
  • Created almost 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

I18n is a golang implementation, provides internationalization support for your application, with different backends support

I18n

I18n provides internationalization support for your application, it supports 2 kinds of storages(backends), the database and file system.

GoDoc

Usage

Initialize I18n with the storage mode. You can use both storages together, the earlier one has higher priority. So in the example, I18n will look up the translation in database first, then continue finding it in the YAML file if not found.

import (
  "github.com/jinzhu/gorm"
  "github.com/qor/i18n"
  "github.com/qor/i18n/backends/database"
  "github.com/qor/i18n/backends/yaml"
)

func main() {
  db, _ := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")

  I18n := i18n.New(
    database.New(&db), // load translations from the database
    yaml.New(filepath.Join(config.Root, "config/locales")), // load translations from the YAML files in directory `config/locales`
  )

  I18n.T("en-US", "demo.greeting") // Not exist at first
  I18n.T("en-US", "demo.hello") // Exists in the yml file

  i18n.Default = "zh-CN" // change the default locale. the original value is "en-US"
}

Once a database has been set for I18n, all untranslated translations inside I18n.T() will be loaded into translations table in the database when compiling the application. For example, we have an untranslated I18n.T("en-US", "demo.greeting") in the example, so I18n will generate this record in the translations table after compiling.

locale key value
en-US demo.greeting  

The YAML file format is

en-US:
  demo:
    hello: "Hello, world"

Use built-in interface for translation management with QOR Admin

I18n has a built-in web interface for translations which is integrated with QOR Admin.

Admin.AddResource(I18n)

To let users able to translate between locales in the admin interface, your "User" need to implement these interfaces.

func (user User) EditableLocales() []string {
	return []string{"en-US", "zh-CN"}
}

func (user User) ViewableLocales() []string {
	return []string{"en-US", "zh-CN"}
}

Refer the online demo.

Use with Golang templates

The easy way to use I18n in a template is to define a t function and register it as FuncMap:

func T(key string, value string, args ...interface{}) string {
  return I18n.Default(value).T("en-US", key, args...)
}

// then use it in the template
{{ t "demo.greet" "Hello, {{$1}}" "John" }} // -> Hello, John

Built-in functions for translations management

I18n has functions to manage translation directly.

// Add Translation
I18n.AddTranslation(&i18n.Translation{Key: "hello-world", Locale: "en-US", Value: "hello world"})

// Update Translation
I18n.SaveTranslation(&i18n.Translation{Key: "hello-world", Locale: "en-US", Value: "Hello World"})

// Delete Translation
I18n.DeleteTranslation(&i18n.Translation{Key: "hello-world", Locale: "en-US", Value: "Hello World"})

Scope and default value

Call Translation with Scope or set default value.

// Read Translation with `Scope`
I18n.Scope("home-page").T("zh-CN", "hello-world") // read translation with translation key `home-page.hello-world`

// Read Translation with `Default Value`
I18n.Default("Default Value").T("zh-CN", "non-existing-key") // Will return default value `Default Value`

Fallbacks

I18n has a Fallbacks function to register fallbacks. For example, registering en-GB as a fallback to zh-CN:

i18n := New(&backend{})
i18n.AddTranslation(&Translation{Key: "hello-world", Locale: "en-GB", Value: "Hello World"})

fmt.Print(i18n.Fallbacks("en-GB").T("zh-CN", "hello-world")) // "Hello World"

To set fallback Locale globally you can use I18n.FallbackLocales. This function accepts a map[string][]string as parameter. The key is the fallback Locale and the []string is the Locales that could fallback to the first Locale.

For example, setting "fr-FR", "de-DE", "zh-CN" fallback to en-GB globally:

I18n.FallbackLocales = map[string][]string{"en-GB": []{"fr-FR", "de-DE", "zh-CN"}}

Interpolation

I18n utilizes a Golang template to parse translations with an interpolation variable.

type User struct {
  Name string
}

I18n.AddTranslation(&i18n.Translation{Key: "hello", Locale: "en-US", Value: "Hello {{.Name}}"})

I18n.T("en-US", "hello", User{Name: "Jinzhu"}) //=> Hello Jinzhu

Pluralization

I18n utilizes cldr to achieve pluralization, it provides the functions p, zero, one, two, few, many, other for this purpose. Please refer to cldr documentation for more information.

I18n.AddTranslation(&i18n.Translation{Key: "count", Locale: "en-US", Value: "{{p "Count" (one "{{.Count}} item") (other "{{.Count}} items")}}"})
I18n.T("en-US", "count", map[string]int{"Count": 1}) //=> 1 item

Ordered Params

I18n.AddTranslation(&i18n.Translation{Key: "ordered_params", Locale: "en-US", Value: "{{$1}} {{$2}} {{$1}}"})
I18n.T("en-US", "ordered_params", "string1", "string2") //=> string1 string2 string1

Inline Edit

You could manage translations' data with QOR Admin interface (UI) after registering it into QOR Admin, however we warn you that it is usually quite hard (and error prone!) to translate a translation without knowing its context...Fortunately, the Inline Edit feature of QOR Admin was developed to resolve this problem!

Inline Edit allows administrators to manage translations from the frontend. Similarly to integrating with Golang Templates, you need to register a func map for Golang templates to render inline editable translations.

The good thing is we have created a package for you to do this easily, it will generate a FuncMap, you just need to use it when parsing your templates:

// `I18n` hold translations backends
// `en-US` current locale
// `true` enable inline edit mode or not, if inline edit not enabled, it works just like the funcmap in section "Integrate with Golang Templates"
inline_edit.FuncMap(I18n, "en-US", true) // => map[string]interface{}{
                                         //     "t": func(string, ...interface{}) template.HTML {
                                         //        // ...
                                         //      },
                                         //    }

License

Released under the MIT License.

More Repositories

1

qor

QOR is a set of libraries written in Go that abstracts common features needed for business applications, CMSs, and E-commerce systems.
Go
5,198
star
2

qor-example

An example application showcasing the QOR SDK
Go
1,241
star
3

admin

Qor Admin - Instantly create a beautiful, cross platform, configurable Admin Interface and API for managing your data in minutes.
JavaScript
898
star
4

auth

Golang Authentication solution
Go
677
star
5

transition

Transition is a Golang state machine implementation
Go
425
star
6

roles

Roles is an authorization library for Golang
Go
140
star
7

validations

Validations is a GORM extension, used to validate models when creating, updating
Go
128
star
8

worker

Worker run jobs in background at scheduled time
Go
61
star
9

media

Media add uploading files to cloud or other destinations with support for image cropping and resizing features to any structs
JavaScript
60
star
10

oss

QOR OSS provides common interface to operate files in cloud storage/filesystem
Go
57
star
11

amazon-pay-sdk-go

Amazon Pay Go SDK
Go
31
star
12

mailer

Mail solution
Go
23
star
13

audited

Audited is used to log last UpdatedBy and CreatedBy for your models
Go
21
star
14

auth_themes

Auth Themes
Go
20
star
15

media_library

Abandoned, use https://github.com/qor/media instead
Go
20
star
16

bindatafs

Compile QOR templates into binary with go-bindata
Go
19
star
17

l10n

L10n make your resources(models) be able to localize into different locales
Go
18
star
18

exchange

QOR exchange provides conversion (import/export) functionality for any Qor.Resource to CSV, Excel file
Go
17
star
19

gomerchant

Stripe, Paygent, and Amazon Pay Adaptors
Go
17
star
20

render

Render Templates
Go
16
star
21

seo

SEO module for QOR3
Go
14
star
22

sorting

Sorting: adds sorting and reordering abilities to your models.
JavaScript
12
star
23

publish2

Version Control with Schedule
Go
11
star
24

widget

Qor Widget - Define some customizable, shareable HTML widgets for different pages
Go
11
star
25

session

Session management
Go
8
star
26

filebox

Filebox could be used to provide access permission control for files, directories
Go
8
star
27

doc

QOR3 documentation
CSS
6
star
28

publish

Publish allow user update a resource but do not show the change in website until it is get "published" for GORM-backend models
Go
6
star
29

activity

Qor Activity: add Comment and Track data/state changes to any Qor Resource support to admin interface
Go
6
star
30

notification

QOR Notification
Go
6
star
31

slug

Slug is an extension for qor.
JavaScript
6
star
32

responder

Responder: Respond differently according to request's accepted mime type
Go
6
star
33

location

Qor Location - Make your struct support pick up location from google map in Qor Admin
JavaScript
5
star
34

assetfs

AssetFileSystem
Go
5
star
35

middlewares

Middlewares Management
Go
5
star
36

serializable_meta

Serializable meta
Go
4
star
37

action_bar

Action Bar in QOR3
Go
4
star
38

cache

Cache Store
Go
4
star
39

redirect_back

A Golang HTTP Handler that redirect back to last URL saved in session
Go
4
star
40

page_builder

Page Builder
JavaScript
3
star
41

metas

Meta Types for Admin
JavaScript
3
star
42

log

Qor Logger
Go
3
star
43

help

Help for QOR ADMIN
JavaScript
3
star
44

banner_editor

Banner Editor in QOR3
JavaScript
2
star
45

application

Application
Go
2
star
46

qor-example-cases

Learn QOR3 by examples
Go
2
star
47

wildcard_router

WildcardRouter handles dynamic routes
Go
2
star
48

variations

Variations
JavaScript
2
star
49

app

App Generator - WIP
Swift
1
star