我正在使用 go 语言通过 go-template 提交 HTML 表单。得到一些奇怪的结果。
基本思想是我有一个名为 Page 的数据结构,其中包含一些元素。该模板填充了一组页面。在模板中,我遍历每个页面并显示其内容。这些内容中的每一个都嵌入到一个 HTML 表单中,并带有各自的链接。单击链接后,它将提交相应的表单。
代码片段如下:
{{range $index, $element := .Pages}}
<form action="/detailNews" id="readMore{{$index}}" method="post" name="readMore{{$index}}">
//displaying elements from each page
<div id="more">
<input name="query" type="hidden" value="{{printf "%s" .Title}}">
<a href="#" onclick="document.readMore{{$index}}.submit()">Read More</a>
</div>
</form>
{{end}}
该代码主要适用于一个小问题。 id 和 name 属性按预期生成输出,例如:readMore0、readMore1 等。
问题出在 onclick 属性填充为以下内容的“a”标记处:document.readMore 0 .submit()、document.readMore 1 .submit() 等。请注意 0、1 周围的 空格。这样,单击链接时将找不到相应的表单。
我想不通这是什么原因。
我们将不胜感激任何帮助。
谢谢, 里普尔
最佳答案
发生这种情况是因为 escaping contexts .
By default, this package assumes that all pipelines produce a plain text string. It adds escaping pipeline stages necessary to correctly and safely embed that plain text string in the appropriate context.
When a data value is not plain text, you can make sure it is not over-escaped by marking it with its type.
Types HTML, JS, URL, and others from content.go can carry safe content that is exempted from escaping.
为了克服它,您应该将页面索引作为类型为 template.JS
的 .Pages
元素结构的一部分传递。 .像这样:
type Page struct {
Id template.JS
Title string
}
关于golang 模板中的 HTML 表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25685797/