相关疑难解决方法(0)

在golang HTML模板中切换或if/elseif/else

我有这个结构:

const (
    paragraph_hypothesis = 1<<iota
    paragraph_attachment = 1<<iota
    paragraph_menu       = 1<<iota
)

type Paragraph struct {
    Type int // paragraph_hypothesis or paragraph_attachment or paragraph_menu
}
Run Code Online (Sandbox Code Playgroud)

我想以Type依赖的方式显示我的段落.

我找到的唯一解决方案是基于专用函数,如isAttachment测试TypeGo和嵌套{{if}}:

{{range .Paragraphs}}
    {{if .IsAttachment}}
        -- attachement presentation code  --
    {{else}}{{if .IsMenu}}
        -- menu --
    {{else}}
        -- default code --
    {{end}}{{end}}
{{end}}
Run Code Online (Sandbox Code Playgroud)

事实上,我有更多类型,这使得它甚至更奇怪,使用IsSomething函数和带有函数的模板混乱{{end}}.

什么是干净的解决方案?go模板中是否有一些switchif/elseif/else解决方案?还是以完全不同的方式处理这些案件?

html templates go go-templates

33
推荐指数
3
解决办法
5万
查看次数

Golang模板变量isset

我创建了一个函数来检查是否定义了变量:

fm["isset"] = func(a interface{}) bool {
        if a == nil || a == "" || a == 0 {
            fmt.Println("is not set")
            return false
        }
        fmt.Println("is set")
        return false
    }

tmpl :=  template.Must(template.New("").Funcs(fm).ParseFiles("templates/header.html"))

err := tmpl.ExecuteTemplate(w, "header", templateData)
Run Code Online (Sandbox Code Playgroud)

在模板中我有:

{{ if isset .Email }}
    email is set
{{ end }}
Run Code Online (Sandbox Code Playgroud)

如果变量包含在templateData(它是包含映射和字符串的自定义结构)中,则此函数有效,但如果变量不存在则会给出错误.

错误是:

executing "header" at <.Email>: can't evaluate field Email in type base.customData
Run Code Online (Sandbox Code Playgroud)

在我的情况下,"base.go"是处理程序,"customData"由以下内容定义:type customData struct{..}.

我希望能够重用模板,并且只有在从处理程序发送一些变量时才显示某些部分.任何想法如何isset在模板端实现变量检查?

我也试过使用:{{ if .Email}} do stuff …

struct if-statement go go-templates

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

go ×2

go-templates ×2

html ×1

if-statement ×1

struct ×1

templates ×1