如何在 Golang 中设置 HTML <select> 元素的默认值?

How can I set the default value for an HTML <select> element in Golang?

我想为列表中的特定项目使用默认值。 我尝试了以下代码,但在操作数 中出现“意外的”= 错误 “ 我该如何处理这个问题?

<select name="location_id">
    {{ range .LocationList}}
        <option value="{{ .Id }}" {{if .Name == .CurrentLocation}}selected{{end}}>{{ .Name }}</option>
    {{ end }} 
</select>

相等性是使用 Go 模板使用 eq 函数实现的,您需要将参数传递给该函数以进行比较。具体来说,if 函数采用 管道 ,在本例中,您向其传递一个函数和一系列参数。 (请参阅 actions and pipelines 的文档。)

正确的语法是:

{{ if eq <arg1> <arg2> }} ... {{ end }}

因此,对于您的示例:

{{ if eq .Name .CurrentLocation }} selected="selected"{{ end }}

(请注意,如果您使用 XHTML,则禁止属性最小化,因此请使用 selected="selected",但对于 HTML,允许 selected。)