首頁 > 後端開發 > Golang > 主體

當欄位未匯出時,如何在 Go 中存取 HTML 範本中的結構體欄位?

Susan Sarandon
發布: 2024-10-24 07:55:30
原創
546 人瀏覽過

How to Access Struct Fields in HTML Templates in Go When Fields Are Unexported?

如何在Go 中存取HTML 範本中的結構體欄位

問題

您想要使用以下方式存取儲存在映射中的結構體字段Go 中的html/template 套件。

解決方案

預設的 Go 範本不允許存取結構體的未匯出欄位。要啟用此功能,您需要透過大寫欄位名稱的第一個字母來匯出欄位。

程式碼範例

使用匯出欄位定義結構:

<code class="go">type Task struct {
   cmd string
   args []string
   Desc string // Note the capital "D"
}</code>
登入後複製

使用匯出的結構初始化對應:

<code class="go">var taskMap = map[string]Task{
    "find": Task{
        cmd: "find",
        args: []string{"/tmp/"},
        Desc: "find files in /tmp dir",
    },
    "grep": Task{
        cmd: "grep",
        args:[]string{"foo","/tmp/*", "-R"},
        Desc: "grep files match having foo",
    },
}</code>
登入後複製
使用匯出的結構初始化對應:

使用匯出的結構初始化對應:

<code class="go">func listHandle(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("index.tmpl")
    t.Execute(w, taskMap)
}</code>
登入後複製

使用匯出的結構初始化對應>

解析並執行範本:
<code class="go"><html>
{{range $key, $value := .}}
   <li>Task Name:        {{$key}}</li>
   <li>Task Value:       {{$value}}</li>
   <li>Task description: {{$value.Desc}}</li>
{{end}}
</html></code>
登入後複製

範本檔案:
<code class="html"><html>

<li>Task Name:        find</li>
<li>Task Value:       {find [/tmp/] find files in /tmp dir}</li>
<li>Task description: find files in /tmp dir</li>

<li>Task Name:        grep</li>
<li>Task Value:       {grep [foo /tmp/* -R] grep files match having foo}</li>
<li>Task description: grep files match having foo</li>

</html></code>
登入後複製
輸出檔:輸出 🎜>範本現在可以存取映射中任務結構的匯出欄位:

以上是當欄位未匯出時,如何在 Go 中存取 HTML 範本中的結構體欄位?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!