如果項目中需要有多語言的展示,類似網站中英文切換,可以使用下面這個方法來實現
主要思路就是,頁面html內容展示的時候,不能固定寫死在頁面上,需要從控制器部分分配過來變量,展示輸出這個變量
這個變量的內容來自一個結構體的成員,該結構體在創建實例的時候,可以根據傳遞參數的不同,實例的成員內容不同
實際展示的地址是:
http://gofly.sopans.com/
控制器部分就是分配變量,在這里是通過get傳遞lang這個參數cn就是中文,en就是英文
engine.GET("/index", tmpl.PageIndex)
//首頁 func PageIndex(c *gin.Context) { lang := c.Query("lang") if lang == "" ||lang!="cn"{ lang = "en" } language:=config.CreateLanguage(lang) c.HTML(http.StatusOK, "index.html", gin.H{ "Copyright":language.WebCopyRight, "WebDesc":language.MainIntro, "SubIntro":language.IndexSubIntro, "Document":language.IndexDocument, "VisitorBtn":language.IndexVisitors, "AgentBtn":language.IndexAgent, "OnlineChat":language.IndexOnlineChat, "IndexSend":language.Send, "Lang":lang, }) }
langguage這個結構體部分,根據不同的參數,創建不同的實例成員
package config type Language struct { WebCopyRight string MainIntro string Send string Notice string IndexSubIntro,IndexVisitors,IndexAgent,IndexDocument,IndexOnlineChat string } func CreateLanguage(lang string)*Language{ var language *Language if lang=="en"{ language=&Language{ WebCopyRight: "TaoShihan", MainIntro: "Simple and Powerful Go language online customer chat system", IndexSubIntro: "GO-FLY, a Vue 2.0-based online customer service instant messaging system for PHP engineers and Golang engineers", IndexDocument:"API Documents", IndexVisitors:"Visitors Here", IndexAgent:"Agents Here", IndexOnlineChat:"Let’s chat. - We're online", Send:"Send", Notice:"Hello and welcome to go-fly - how can we help?", } } if lang=="cn"{ language=&Language{ WebCopyRight: "陶士涵的菜地版權所有", MainIntro:"極簡強大的Go語言在線客服系統", IndexSubIntro:"GO-FLY,一套為PHP工程師、Golang工程師准備的基於 Vue 2.0的在線客服即時通訊系統", IndexVisitors:"訪客入口", IndexAgent:"客服入口", IndexDocument:"接口文檔", IndexOnlineChat:"在線咨詢", Send:"發送", Notice:"歡迎您訪問go-fly!有什么我能幫助您的?", } } return language }