英文:
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
官方文档中对于模板中的or
、and
、eq
和neq
有解释。你可以在这里阅读有关模板函数的信息。
需要记住的是,模板中提供的函数是前缀表示法(波兰表示法)。例如,不等于运算符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)
}
}
}
英文:
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)
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论