首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在golang HTML模板中使用Switch或if/else if/else

在golang HTML模板中使用Switch或if/else if/else
EN

Stack Overflow用户
提问于 2013-06-07 21:34:57
回答 3查看 89.4K关注 0票数 49

我有这样的结构:

代码语言:javascript
复制
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
}

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

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

代码语言:javascript
复制
{{range .Paragraphs}}
    {{if .IsAttachment}}
        -- attachement presentation code  --
    {{else}}{{if .IsMenu}}
        -- menu --
    {{else}}
        -- default code --
    {{end}}{{end}}
{{end}}

事实上,我有更多的类型,这使得它更奇怪,用IsSomething函数和那些{{end}}把Go代码和模板弄得乱七八糟。

干净的解决方案是什么?go模板中有没有switchif/elseif/else解决方案?或者是一种完全不同的方式来处理这些情况?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-06-07 21:55:24

模板是无逻辑的。他们不应该有这样的逻辑。您可以拥有的最大逻辑是一堆if

在这种情况下,你应该这样做:

代码语言:javascript
复制
{{if .IsAttachment}}
    -- attachment presentation code --
{{end}}

{{if .IsMenu}}
    -- menu --
{{end}}

{{if .IsDefault}}
    -- default code --
{{end}}
票数 46
EN

Stack Overflow用户

发布于 2018-07-12 22:36:29

可以,您可以使用{{else if .IsMenu}}

票数 39
EN

Stack Overflow用户

发布于 2013-06-08 10:43:51

您可以通过向template.FuncMap添加自定义函数来实现switch功能。

在下面的示例中,我定义了一个函数printPara (paratype int) string,它接受您定义的段落类型之一,并相应地更改其输出。

请注意,在实际模板中,.Paratype是通过管道传递给printpara函数的。这就是如何在模板中传递参数。请注意,添加到FuncMaps的函数的输出参数的数量和形式有限制。This page有一些很好的信息,以及第一个链接。

代码语言:javascript
复制
package main

import (
    "fmt"
    "os"
    "html/template"
)

func main() {

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

    const text = "{{.Paratype | printpara}}\n" // A simple test template

    type Paragraph struct {
        Paratype int
    }

    var paralist = []*Paragraph{
        &Paragraph{paragraph_hypothesis},
        &Paragraph{paragraph_attachment},
        &Paragraph{paragraph_menu},
    }

    t := template.New("testparagraphs")

    printPara := func(paratype int) string {
        text := ""
        switch paratype {
        case paragraph_hypothesis:
            text = "This is a hypothesis\n"
        case paragraph_attachment:
            text = "This is an attachment\n"
        case paragraph_menu:
            text = "Menu\n1:\n2:\n3:\n\nPick any option:\n"
        }
        return text
    }

    template.Must(t.Funcs(template.FuncMap{"printpara": printPara}).Parse(text))

    for _, p := range paralist {
        err := t.Execute(os.Stdout, p)
        if err != nil {
            fmt.Println("executing template:", err)
        }
    }
}

产生:

这只是一个假设

这是一个附件

菜单

1:

2:

3:

选择任一选项:

Playground link

希望这会有帮助,我非常确定代码可以清理一下,但我已经尝试与您提供的示例代码保持密切联系。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16985469

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档