【问题标题】:How can I set the default value for an HTML <select> element in Golang?如何在 Golang 中为 HTML <select> 元素设置默认值?
【发布时间】:2018-09-22 14:40:25
【问题描述】:

我想为列表中的特定项目使用默认值。 我尝试了以下代码,但出现“unexpected "=" in operand 错误 " 我该如何处理这个问题?

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

【问题讨论】:

  • {{if eq .Name .CurrentLocation}}
  • 非常感谢@MartinGallagher。效果很好

标签: html templates go html-select


【解决方案1】:

平等是使用 Go 模板使用 eq 函数实现的,您需要将参数传递给该函数以进行比较。具体来说,if 函数采用 管道,在这种情况下,您将向其传递一个函数和一系列参数。 (请参阅 actionspipelines 的文档。)

正确使用的语法是:

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

所以,对于你的例子:

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

(注意如果你使用 XHTML,属性最小化是被禁止的,所以使用selected="selected",但是对于 HTML,selected 是允许的。)

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2021-11-19
    • 2020-07-22
    • 2017-09-15
    • 1970-01-01
    相关资源
    最近更新 更多