go-vise

Constrained Size Output Virtual Machine
Info | Log | Files | Refs | README | LICENSE

gettext.go (1625B)


      1 package resource
      2 
      3 import (
      4 	"context"
      5 
      6 	gotext "gopkg.in/leonelquinteros/gotext.v1"
      7 
      8 	"git.defalsify.org/vise.git/lang"
      9 )
     10 
     11 const (
     12 	PoDomain            = "default"
     13 	TemplateKeyPoDomain = "x-vise"
     14 	MenuKeyPoDomain     = "x-vise_menu"
     15 )
     16 
     17 type PoResource struct {
     18 	*MenuResource
     19 	path            string
     20 	defaultLanguage lang.Language
     21 	tr              map[string]*gotext.Locale
     22 }
     23 
     24 func NewPoResource(defaultLanguage lang.Language, path string) *PoResource {
     25 	o := &PoResource{
     26 		MenuResource:    NewMenuResource(),
     27 		path:            path,
     28 		defaultLanguage: defaultLanguage,
     29 		tr:              make(map[string]*gotext.Locale),
     30 	}
     31 	return o.WithLanguage(defaultLanguage)
     32 }
     33 
     34 func (p *PoResource) WithLanguage(ln lang.Language) *PoResource {
     35 	o := gotext.NewLocale(p.path, ln.Code)
     36 	o.AddDomain(PoDomain)
     37 	if ln.Code == p.defaultLanguage.Code {
     38 		o.AddDomain(TemplateKeyPoDomain)
     39 		o.AddDomain(MenuKeyPoDomain)
     40 	}
     41 	p.tr[ln.Code] = o
     42 	return p
     43 }
     44 
     45 func (p *PoResource) get(ctx context.Context, sym string, domain string, menu bool) (string, error) {
     46 	s := sym
     47 	ln, ok := lang.LanguageFromContext(ctx)
     48 	if !ok {
     49 		ln = p.defaultLanguage
     50 	}
     51 	o, ok := p.tr[p.defaultLanguage.Code]
     52 	if ok {
     53 		keyDomain := TemplateKeyPoDomain
     54 		if menu {
     55 			keyDomain = MenuKeyPoDomain
     56 		}
     57 		s = o.GetD(keyDomain, sym)
     58 		o, ok := p.tr[ln.Code]
     59 		if ok {
     60 			s = o.GetD(domain, s)
     61 		}
     62 	}
     63 	return s, nil
     64 }
     65 
     66 func (p *PoResource) GetMenu(ctx context.Context, sym string) (string, error) {
     67 	return p.get(ctx, sym, PoDomain, true)
     68 }
     69 
     70 func (p *PoResource) GetTemplate(ctx context.Context, sym string) (string, error) {
     71 	return p.get(ctx, sym, PoDomain, false)
     72 }