github.com/erda-project/erda-infra@v1.0.9/providers/legacy/httpendpoints/i18n/template.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package i18n 16 17 import ( 18 "fmt" 19 "regexp" 20 ) 21 22 // Template . 23 type Template struct { 24 key string 25 content string 26 } 27 28 // NewTemplate . 29 func NewTemplate(key string, content string) *Template { 30 return &Template{key: key, content: content} 31 } 32 33 // Render . 34 func (t *Template) Render(args ...interface{}) string { 35 return fmt.Sprintf(t.content, args...) 36 } 37 38 // Key . 39 func (t *Template) Key() string { return t.key } 40 41 // Content . 42 func (t *Template) Content() string { return t.content } 43 44 // RenderByKey Render by key eg: {{keyName}} 45 func (t *Template) RenderByKey(params map[string]string) string { 46 reg := regexp.MustCompile(`{{.+?}}`) 47 result := reg.ReplaceAllStringFunc(t.content, func(s string) string { 48 key := s[2 : len(s)-2] 49 value, ok := params[key] 50 if ok { 51 return value 52 } 53 return s 54 }) 55 return result 56 }