繁体   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