<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                ## 使用 text/template和HTML/templates包 Go為模板操作提供了豐富的支持。嵌套模板,導入函數,表示變量,迭代數據等等都很簡單。如果需要比CSV數據格式更復雜的東西,模板可能是一個不錯的解決方案。 模板的另一個應用是網站的頁面渲染。當我們想要將服務器端數據呈現給客戶端時,模板可以很好地滿足要求。起初,Go模板可能會讓人感到困惑。 本章將探討如何使用模板。 ### 實踐 1. 建立templates.go: ``` package templates import ( "os" "strings" "text/template" ) const sampleTemplate = ` This template demonstrates printing a {{ .Variable | printf "%#v" }}. {{if .Condition}} If condition is set, we'll print this {{else}} Otherwise, we'll print this instead {{end}} Next we'll iterate over an array of strings: {{range $index, $item := .Items}} {{$index}}: {{$item}} {{end}} We can also easily import other functions like strings.Split then immediately used the array created as a result: {{ range $index, $item := split .Words ","}} {{$index}}: {{$item}} {{end}} Blocks are a way to embed templates into one another {{ block "block_example" .}} No Block defined! {{end}} {{/* This is a way to insert a multi-line comment */}} ` const secondTemplate = ` {{ define "block_example" }} {{.OtherVariable}} {{end}} ` // RunTemplate初始化模板并展示了對模板的基本操作 func RunTemplate() error { data := struct { Condition bool Variable string Items []string Words string OtherVariable string }{ Condition: true, Variable: "variable", Items: []string{"item1", "item2", "item3"}, Words: "another_item1,another_item2,another_item3", OtherVariable: "I'm defined in a second template!", } funcmap := template.FuncMap{ "split": strings.Split, } // 這里可以鏈式調用 t := template.New("example") t = t.Funcs(funcmap) // 我們可以使用Must來替代它 // template.Must(t.Parse(sampleTemplate)) t, err := t.Parse(sampleTemplate) if err != nil { return err } // 為了模擬長時間操作我們通過克隆創建另一個模板 然后解析它 t2, err := t.Clone() if err != nil { return err } t2, err = t2.Parse(secondTemplate) if err != nil { return err } // 將數據填充后的模板寫入標準輸出 err = t2.Execute(os.Stdout, &data) if err != nil { return err } return nil } ``` 2. 建立template_files.go: ``` package templates import ( "io/ioutil" "os" "path/filepath" "text/template" ) //CreateTemplate會創建一個包含數據的模板文件 func CreateTemplate(path string, data string) error { return ioutil.WriteFile(path, []byte(data), os.FileMode(0755)) } // InitTemplates在文件夾中設置一系列的模板文件 func InitTemplates() error { tempdir, err := ioutil.TempDir("", "temp") if err != nil { return err } // 在操作完成后全部都將被刪除 defer os.RemoveAll(tempdir) err = CreateTemplate(filepath.Join(tempdir, "t1.tmpl"), ` Template 1! {{ .Var1 }} {{ block "template2" .}} {{end}} {{ block "template3" .}} {{end}} `) if err != nil { return err } err = CreateTemplate(filepath.Join(tempdir, "t2.tmpl"), ` {{ define "template2"}}Template 2! {{ .Var2 }}{{end}} `) if err != nil { return err } err = CreateTemplate(filepath.Join(tempdir, "t3.tmpl"), ` {{ define "template3"}}Template 3! {{ .Var3 }}{{end}} `) if err != nil { return err } pattern := filepath.Join(tempdir, "*.tmpl") // 組合所有匹配glob的文件并將它們組合成一個模板 tmpl, err := template.ParseGlob(pattern) if err != nil { return err } // Execute函數可以運用于map和struct tmpl.Execute(os.Stdout, map[string]string{ "Var1": "Var1!!", "Var2": "Var2!!", "Var3": "Var3!!", }) return nil } ``` 3. 建立 html_templates.go: ``` package templates import ( "fmt" "html/template" "os" ) // HTMLDifferences 展示了html/template 和 text/template的一些不同 func HTMLDifferences() error { t := template.New("html") t, err := t.Parse("<h1>Hello! {{.Name}}</h1>\n") if err != nil { return err } // html/template自動轉義不安全的操作,比如javascript注入 // 這會根據變量的位置不同而呈現不完全相同的結果 err = t.Execute(os.Stdout, map[string]string{"Name": "<script>alert('Can you see me?')</script>"}) if err != nil { return err } // 你也可以手動調用轉義器 fmt.Println(template.JSEscaper(`example <example@example.com>`)) fmt.Println(template.HTMLEscaper(`example <example@example.com>`)) fmt.Println(template.URLQueryEscaper(`example <example@example.com>`)) return nil } ``` 4. 以上示例打印顯示較長,大家可自行運行查看。 ### 說明 Go有兩個模板包 - text/template和html/template。這兩個包的部分函數看起來非常相似,實際功能也確實如此。通常,使用html/template來呈現網站。模板是純文本,但變量和函數可以在大括號塊內使用。 模板包還提供了處理文件的便捷方法。示例在臨時目錄中創建了許多模板,然后使用一行代碼讀取所有模板。 html/template包是對text/template包的包裝。所有模板示例都對html/template包同樣適用,除了import語句無需其他任何修改。HTML模板提供了上下文感知安全性的額外好處。這可以防止諸如JavaScript注入之類的事情。 模板包能夠滿足你對頁面操作的期望。在向HTML和JavaScript發布結果時,你可以輕松組合模板,添加應用程序邏輯并確保安全性。 * * * * 學識淺薄,錯誤在所難免。歡迎在群中就本書提出修改意見,以饗后來者,長風拜謝。 Golang中國(211938256) beego實戰(258969317) Go實踐(386056972)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看