簡體   English   中英

如何將 main.go 文件中的變量調用到 html 文件?

[英]How to call a variable from main.go file to an html file?

在這段代碼中,我在main.go中有一個 about 函數,我試圖在其中獲取about.htmlContent變量數據。 我在about.html調用了{{.Content}}但是當我填充 textarea 時它沒有顯示任何結果。 如何處理?

關於.html

{{template "base" .}}
{{define "title"}} About {{end}}
{{define "body"}}
    {{if .Success}}
        {{.Content}}
    {{else}}
        <h1>About</h1>
        <form action="/about" method="POST" name="about" id="about">
            <div>
                <label>Content</label>
                <textarea name="content"></textarea>
            </div>
            <div>
                <input type="submit" value="Submit">
            </div>
        </form>
    {{end}}
{{end}}

main.go

func makeTemlate(base string) *template.Template {
    files := []string{base, "ui/html/footer.html", "ui/html/base.html"}
    return template.Must(template.ParseFiles(files...))
}

var aboutTmpl  = makeTemlate("ui/html/about.html")

type Details struct {
    Content string
}

func about(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        aboutTmpl.Execute(w, nil)
        return
    }
    details := Details{
        Content: r.FormValue("content"),
    }
    _ = details
    aboutTmpl.Execute(w, struct{ Success bool }{true})
}

func main() {
    http.HandleFunc("/about", about)
    log.Println("Starting the server at :4000")
    http.ListenAndServe(":4000", nil)
}

以下是給定 OP 代碼的測試實現。

我使用 go1.15 usng GOPATH,將自己設置在test/d/htt

我只會通過將內容變量添加到模板參數來修復您的處理程序,並且它會起作用。

$ touch main.go
$ touch handler.go
$ touch handler_test.go
$ mkdir -p ui/html
$ touch ui/html/about.html
$ touch ui/html/footer.html
$ touch ui/html/base.html

main.go

package main

import (
    "html/template"
    "log"
    "net/http"
)

func makeTemlate(base string) *template.Template {
    files := []string{base, "ui/html/footer.html", "ui/html/base.html"}
    return template.Must(template.ParseFiles(files...))
}

func main() {
    http.HandleFunc("/about", About)
    log.Println("Starting the server at :4000")
    http.ListenAndServe(":4000", nil)
}

處理程序

package main

import (
    "net/http"
)

var aboutTmpl = makeTemlate("ui/html/about.html")

type Details struct {
    Success bool
    Content string
}

func About(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        aboutTmpl.Execute(w, nil)
        return
    }
    details := Details{
        Success: true,
        Content: r.FormValue("content"),
    }
    aboutTmpl.Execute(w, details)
}

handler_test.go

package main

import (
    "bytes"
    "io"
    "net/http"
    "net/http/httptest"
    "net/url"
    "strings"
    "testing"
)

func TestAboutHandlerGetMethod(t *testing.T) {
    req, err := http.NewRequest("GET", "/about", nil)
    if err != nil {
        t.Fatal(err)
    }

    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(About)
    handler.ServeHTTP(rr, req)

    if status := rr.Code; status != http.StatusOK {
        t.Errorf("handler returned wrong status code: got %v want %v",
            status, http.StatusOK)
    }
    var buf bytes.Buffer
    io.Copy(&buf, rr.Body)
    b := buf.Bytes()
    if !bytes.Contains(b, []byte(`<form action="/about" method="POST" name="about" id="about">`)) {
        t.Errorf("form must be displayed when fetch with GET method, got=\n%s", b)
    }
}

func TestAboutHandlerPostMethod(t *testing.T) {
    form := url.Values{}
    form.Add("content", "Hellocontent")
    req, err := http.NewRequest("POST", "/about", strings.NewReader(form.Encode()))
    if err != nil {
        t.Fatal(err)
    }
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(About)
    handler.ServeHTTP(rr, req)

    if status := rr.Code; status != http.StatusOK {
        t.Errorf("handler returned wrong status code: got %v want %v",
            status, http.StatusOK)
    }
    var buf bytes.Buffer
    io.Copy(&buf, rr.Body)
    b := buf.Bytes()
    if bytes.Contains(b, []byte(`<form action="/about" method="POST" name="about" id="about">`)) {
        t.Errorf("form must not be displayed when fetch with POST method, got=\n%s", b)
    }
    if !bytes.Contains(b, []byte(`Hellocontent`)) {
        t.Errorf("output must include the dispay of the posted content, got=\n%s", b)
    }
}

用戶界面/html/base.html

{{define "base"}}
    {{template "title" .}}
    {{template "body" .}}
{{end}}

ui/html/about.html

{{template "base" .}}
{{define "title"}} About {{end}}
{{define "body"}}
    {{if .Success}}
        {{.Content}}
    {{else}}
        <h1>About</h1>
        <form action="/about" method="POST" name="about" id="about">
            <div>
                <label>Content</label>
                <textarea name="content"></textarea>
            </div>
            <div>
                <input type="submit" value="Submit">
            </div>
        </form>
    {{end}}
{{end}}

ui/html/footer.html

// left empty...

最后,我運行go test -v .

=== RUN   TestAboutHandlerGetMethod
--- PASS: TestAboutHandlerGetMethod (0.00s)
=== RUN   TestAboutHandlerPostMethod
--- PASS: TestAboutHandlerPostMethod (0.00s)
PASS
ok      test/d/htt  0.005s

最后說明,http post 測試可以使用http.PostForm編寫,為了簡化和干燥, https: http.PostForm

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM