Go text/template Form handling, with custom FuncMap – function returning blank string outputs garbage

huangapple go评论86阅读模式
英文:

Go text/template Form handling, with custom FuncMap - function returning blank string outputs garbage

问题

使用Go的html/template功能,结合自定义的FuncMap。我定义的自定义函数"isChecked(checkName string, form url.Values)"会在表单中存在名为checkName的复选框时返回字符串"checked",否则返回空字符串。它的功能正常,但有个奇怪的问题是,在未选中的复选框的完成HTML中,我看到了字符串"ZgotmplZ",而实际上应该没有任何字符串。以下是设置FuncMap的main.go程序:

package main

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

var tpl *template.Template

func init() {
	tpl = template.Must(template.New("").Funcs(fm).ParseFiles("templates/check-box.html"))
}

var fm = template.FuncMap{
	"isChecked": isChecked,
}

func isChecked(checkName string, form url.Values) string {
	if form.Has(checkName) {
		return "checked"
	}
	return ""
}

func checkboxHandler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		log.Fatalln(err)
	}

	err = tpl.ExecuteTemplate(w, "check-box.html", r.Form)
	if err != nil {
		log.Fatalln(err)
	}
}

func main() {
	http.HandleFunc("/checkbox/", checkboxHandler)

	err := http.ListenAndServe(":8080", nil)
}

以下是模板:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkbox Control</title>
</head>
<body>

    <h1>Go html/template Form Handling - Checkbox</h1>

    <div>
    Form Data: {{.}}
    </div>

    <form action="/checkbox/" method="POST">

        <div>
            <label for="checkbox">Check Box</label>
            <input type="checkbox" name="check1" id="checkbox" value="check1" {{isChecked "check1" .}}>Check 1
            <input type="checkbox" name="check2" id="checkbox" value="check2" {{isChecked "check2" .}}>Check 2
            <input type="checkbox" name="check3" id="checkbox" value="check3" {{isChecked "check3" .}}>Check 3
        </div>

        <div>
            <button type="submit">Submit</button>
        </div>

    </form>

</body>
</html>

提交表单并选中复选框的结果是正确的。但是当我查看源代码时,对于未选中的复选框,我得到了一个奇怪的字符串"ZgotmplZ"(换句话说,似乎FuncMap中的自定义函数没有为未选中的复选框返回空字符串):

        <div>
            <label for="checkbox">Check Box</label>
            <input type="checkbox" name="check1" id="checkbox" value="check1" checked>Check 1
            <input type="checkbox" name="check2" id="checkbox" value="check2" ZgotmplZ>Check 2
            <input type="checkbox" name="check3" id="checkbox" value="check3" ZgotmplZ>Check 3
        </div>

同时,我想知道是否有其他建议可以将复选框的"checked"状态传递给HTML模板。

谢谢!

英文:

Using Go html/template functionality, with custom FuncMap. The custom function I've defined "isChecked(checkName string, form url.Values)" returns the string "checked" if the checkbox with checkName exists in the form, and a blank string if it does not. It works fine, but the curious thing is on the completed HTML for an un-checked checkbox, I am seeing the string "ZgotmplZ" where there should be no string at all. Here is the main.go program that sets up the FuncMap:

package main

import (
	&quot;fmt&quot;
	&quot;html/template&quot;
	&quot;log&quot;
	&quot;net/http&quot;
	&quot;net/url&quot;
)

var tpl *template.Template

func init() {
	tpl = template.Must(template.New(&quot;&quot;).Funcs(fm).ParseFiles(&quot;templates/check-box.html&quot;))
}

var fm = template.FuncMap{
	&quot;isChecked&quot;: isChecked,
}

func isChecked(checkName string, form url.Values) string {
	if form.Has(checkName) {
		return &quot;checked&quot;
	}
	return &quot;&quot;
}

func checkboxHandler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		log.Fatalln(err)
	}

	err = tpl.ExecuteTemplate(w, &quot;check-box.html&quot;, r.Form)
	if err != nil {
		log.Fatalln(err)
	}
}

func main() {
	http.HandleFunc(&quot;/checkbox/&quot;, checkboxHandler)

	err := http.ListenAndServe(&quot;:8080&quot;, nil)
}

Here is the template:

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Checkbox Control&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;h1&gt;Go html/template Form Handling - Checkbox&lt;/h1&gt;

    &lt;div&gt;
    Form Data: {{.}}
    &lt;/div&gt;

    &lt;form action=&quot;/checkbox/&quot; method=&quot;POST&quot;&gt;

        &lt;div&gt;
            &lt;label for=&quot;checkbox&quot;&gt;Check Box&lt;/label&gt;
            &lt;input type=&quot;checkbox&quot; name=&quot;check1&quot; id=&quot;checkbox&quot; value=&quot;check1&quot; {{isChecked &quot;check1&quot; .}}&gt;Check 1
            &lt;input type=&quot;checkbox&quot; name=&quot;check2&quot; id=&quot;checkbox&quot; value=&quot;check2&quot; {{isChecked &quot;check2&quot; .}}&gt;Check 2
            &lt;input type=&quot;checkbox&quot; name=&quot;check3&quot; id=&quot;checkbox&quot; value=&quot;check3&quot; {{isChecked &quot;check3&quot; .}}&gt;Check 3
        &lt;/div&gt;

        &lt;div&gt;
            &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;
        &lt;/div&gt;

    &lt;/form&gt;

&lt;/body&gt;
&lt;/html&gt;

The result of submitting the form and checking the checkboxes is good. But when I examine source, I get this funny string "ZgotmplZ" for checkboxes that are not checked (in other words, it seems the custom function in the FuncMap is not returning a blank string for un-checked checkboxes):

        &lt;div&gt;
            &lt;label for=&quot;checkbox&quot;&gt;Check Box&lt;/label&gt;
            &lt;input type=&quot;checkbox&quot; name=&quot;check1&quot; id=&quot;checkbox&quot; value=&quot;check1&quot; checked&gt;Check 1
            &lt;input type=&quot;checkbox&quot; name=&quot;check2&quot; id=&quot;checkbox&quot; value=&quot;check2&quot; ZgotmplZ&gt;Check 2
            &lt;input type=&quot;checkbox&quot; name=&quot;check3&quot; id=&quot;checkbox&quot; value=&quot;check3&quot; ZgotmplZ&gt;Check 3
        &lt;/div&gt;

Also wondering if anyone has other suggestions on how to propate checkbox "checked" states to an html template.

Thanks!

答案1

得分: 0

模板发出ZgotmplZ,因为它不喜欢在属性上下文中出现空字符串。通过以下方式进行修复。

从isChecked函数返回bool类型:

func isChecked(checkName string, form url.Values) bool {
    return form.Has(checkName) 
}

在模板中使用if语句:

{{if isChecked "check1" .}}checked{{end}}
英文:

The template emits ZgotmplZ because it does not like an empty string in an attribute context. Fix by doing the following.

Return bool from isChecked:

func isChecked(checkName string, form url.Values) bool {
     return form.Has(checkName) 
}

Use an if action in the template:

{{if isChecked &quot;check1&quot; .}}checked{{end}}

huangapple
  • 本文由 发表于 2022年10月23日 04:09:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/74166762.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定