Skip to main content

i18n

Zog has built in support for i18n with two types of language support:

First Party Languages (maintained by Zog maintainers and guaranteed to be up to date):

  • English
  • Spanish

Third Party Languages (community maintained, may lag behind):

You can add your own custom languages or even make a package for a new language very easily. We encourage you to submit pull requests to update error message translations if you find any issues or want to contribute a new language.

NOTE: I recommend you also read the errors page which will give you a bunch of options for creating custom error messages which you can use in conjunction with i18n.

Changing the default language for error messages

Lets imagine you are building an application that is only in Spanish. You can change the default language for error messages like this:

import (
"github.com/Oudwins/zog/conf" // import the zog configuration package
"github.com/Oudwins/zog/i18n/es" // import the built in spanish translations
)

// override the default error map
conf.DefaultErrMsgMap = es.Map // now all errors will be in spanish!

This will be a little bit harder if you want to change the language to one that is not built in by default into Zog. But it is still very easy to do. You just have to implement your own LangMap. Checkout the spanish or english language maps copy one of those and translate the error messages to your language. And after, how about publishing it as a package and make it available to everyone?

Supporting Multiple Languages

This is what the i18n package is for. It allows you to support multiple languages in a simple and easy way. Below is an example of how to make Zog support both English and Spanish errors and configure the language for each parsing execution. Again, if you need to support languages not built in to Zog you will have to implement your own LangMaps.

// Somewhere when you start your app
import (
"github.com/Oudwins/zog/i18n" // import the i18n library
"github.com/Oudwins/zog/i18n/en"
"github.com/Oudwins/zog/i18n/es" // import any of the supported language maps or build your own
)

i18n.SetLanguagesErrsMap(map[string]i18n.LangMap{
"es": es.Map,
"en": en.Map,
},
"es", // default language
i18n.WithLangKey("langKey"), // (optional) default lang key is "lang" and is stored in i18n.LangKey
)


// Now when we parse
schema.Parse(data, &dest, z.WithCtxValue("langKey", "es")) // get spanish errors
schema.Parse(data, &dest, z.WithCtxValue("langKey", "en")) // get english errors
schema.Parse(data, &dest) // get default lang errors (spanish in this case)