如何为HTML< select>设置默认值. Golang中的元素? [英] How can I set the default value for an HTML <select> element in Golang?
问题描述
我想为列表中的特定项目使用默认值. 我尝试了以下代码,但在操作数中出现"意外" =""错误 " 我该如何解决这个问题?
I want use a default value for a specific item in a list. I tried the following code but I got an error of "unexpected "=" in operand " How can I handle this problem?
<select name="location_id">
{{ range .LocationList}}
<option value="{{ .Id }}" {{if .Name == .CurrentLocation}}selected{{end}}>{{ .Name }}</option>
{{ end }}
</select>
推荐答案
使用Go模板并使用eq
函数来实现相等性,您需要向其传递参数以进行比较.具体来说,if
函数采用了 pipeline ,在这种情况下,您将传递一个函数和一系列参数. (请参阅有关操作和
Equality is implemented using Go templates using the eq
function, to which you need to pass the arguments to compare. Specifically, the if
function takes a pipeline, to which in this case you pass a function and a series of arguments. (See the docs for actions and pipelines.)
要使用的正确语法是:
{{ if eq <arg1> <arg2> }} ... {{ end }}
所以,例如:
{{ if eq .Name .CurrentLocation }} selected="selected"{{ end }}
(如果您使用的是XHTML,则禁止最小化注释属性,因此请使用selected="selected"
,但对于HTML,允许使用selected
.)
(note attribute minimization is forbidden if you're using XHTML, so use selected="selected"
, but for HTML, selected
is permitted.)
这篇关于如何为HTML< select>设置默认值. Golang中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!