小编Tob*_*yer的帖子

比较Go模板中的两个变量

在传递给模板的数据中,我有两个变量TypeRes.Type我想进行比较以为select字段预选择一个选项。

为了说明我的问题,我创建了这个简化的版本:

package main

import (
    "bufio"
    "bytes"
    "html/template"
    "log"
)

type Result struct{ Type string }

func main() {
    types := map[string]string{
        "FindAllString":      "FindAllString",
        "FindString":         "FindString",
        "FindStringSubmatch": "FindStringSubmatch",
    }
    res := &Result{Type: "findAllString"}

    templateString := `
    <select name="type">
        {{ range $key,$value := .Types }}
            {{ if eq $key .Res.Type }}
                <option value="{{$key}}" selected>{{$value}}</option>
            {{ else }}
                <option value="{{$key}}">{{$value}}</option>
            {{ end }}
        {{ end }}
    </select>`
    t, err := template.New("index").Parse(templateString)
    if err != nil {
        panic(err) …
Run Code Online (Sandbox Code Playgroud)

html loops go go-templates

4
推荐指数
1
解决办法
3261
查看次数

标签 统计

go ×1

go-templates ×1

html ×1

loops ×1