如何为HTML< select>设置默认值. Golang中的元素? [英] How can I set the default value for an HTML <select> element in Golang?

查看:80
本文介绍了如何为HTML< select>设置默认值. 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&lt; select&gt;设置默认值. Golang中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆