如何在Go模板中使用管道运算符“or”?

huangapple go评论100阅读模式
英文:

How to use "or" with pipelines in go templates?

问题

你可以使用"or"运算符来连接多个比较参数,或者你可以在哪里找到一些示例呢?在官方文档中似乎没有相关内容。

if (x == "value" || y == "other") || (x != "a") && (y == "b"){
  print("hello")
}
英文:

How can I use the "or" operator with multiple comparison arguments or any idea where I can find some examples? There seem to be none on the official doc.

if (x == "value" && y == "other") || (x != "a") && (y == "b"){
  print("hello")
}

答案1

得分: 7

官方文档中对于模板中的orandeqneq有解释。你可以在这里阅读有关模板函数的信息。

需要记住的是,模板中提供的函数是前缀表示法(波兰表示法)。例如,不等于运算符ne 1 2会返回true,因为它的两个参数1和2不相等。这是一个使用模板函数将你给出的表达式改写为前缀表示法的示例。

package main

import (
	"os"
	"text/template"
)

type Values struct {
	Title, X, Y string
}

func main() {
	// 括号用于说明运算顺序,但可以省略
	const given_template = `
	{{ if or (and (eq .X "value") (eq .Y "other")) (and (ne .X "a") (eq .Y "b")) }}
	print("hello, {{.Title}}")
	{{end}}`

	values := []Values{
		Values{Title: "first", X: "value", Y: "other"},
		Values{Title: "second", X: "not a", Y: "b"},
		Values{Title: "neither", X: "Hello", Y: "Gopher"},
	}

	t := template.Must(template.New("example").Parse(given_template))

	for _, value := range values {
		err := t.Execute(os.Stdout, &value)

		if err != nil {
			panic(err)
		}
	}
}

Go Playground

英文:

The official docs do have explanations for for or, and, eq, and neq for use in templates. You can read about template functions here.

The thing to remember is that the functions provided in templates are prefix notation (Polish Notation). For example the not equal operator ne 1 2 would evaluate to true given that its two arguments 1 and 2 are not equal. Here is an example of a template that uses your given expression rewritten in prefix with template functions.

package main

import (
    "os"
    "text/template"
)

type Values struct {
    Title, X, Y string
}

func main() {
        // Parenthesis are used to illustrate order of operation but could be omitted
    const given_template = `
    {{ if or (and (eq .X "value") (eq .Y "other")) (and (ne .X "a") (eq .Y "b")) }}
    print("hello, {{.Title}}")
    {{end}}`

    values := []Values{
	    Values{Title: "first", X: "value", Y: "other"},
	    Values{Title: "second", X: "not a", Y: "b"},
	    Values{Title: "neither", X: "Hello", Y: "Gopher"},
    }

    t := template.Must(template.New("example").Parse(given_template))

    for _, value := range values {
	    err := t.Execute(os.Stdout, &value)

	    if err != nil {
		    panic(err)
	    }
    }
}

Go Playground

huangapple
  • 本文由 发表于 2015年5月16日 07:46:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/30270296.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定