如何在Go模板中比较字符串?

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

How to compare strings in go templates?

问题

我想展示那些具有.metadata.labels.app设置为"myapp"的条目。

命令:

kubectl get pods -o go-template --template="{{range .items}}{{if eq .metadata.labels.app "myapp"}}{{.metadata.name}} {{end}}{{end}}"

它会报错:

output:1: function "myapp" not defined

结构看起来像这样:

- apiVersion: v1
  kind: Pod
  metadata:
    creationTimestamp: 2017-09-15T08:18:26Z
    generateName: myapp-2830765207-
    labels:
      app: myapp
      pod-template-hash: "2830765207"
    name: myapp-2830765207-dh359
    namespace: default
英文:

I'd like to show entries that have .metadata.labels.app set to "myapp" value.

Command:

kubectl get pods -o go-template --template="{{range .items}}{{if eq .metadata.labels.app "myapp"}}{{.metadata.name}} {{end}}{{end}}"

It gives an error:

>output:1: function "myapp" not defined

The structures look like this:

- apiVersion: v1
  kind: Pod
  metadata:
    creationTimestamp: 2017-09-15T08:18:26Z
    generateName: myapp-2830765207-
    labels:
      app: myapp
      pod-template-hash: "2830765207"
    name: myapp-2830765207-dh359
    namespace: default

答案1

得分: 7

我以前没有使用过kubetcl,但我对一般的shell命令很熟悉,从中我可以告诉你一个可能出错的地方,也许这就是你需要的全部。 (我对Go模板也有一些了解,你的字符串比较看起来没问题。)在你的模板和模板内部使用双引号,实际上会在"myapp"中的第一个双引号处关闭作为模板传递的字符串。在模板周围使用单引号应该会有所帮助:

kubectl get pods -o go-template --template='{{range .items}}{{if eq .metadata.labels.app "myapp"}}{{.metadata.name}} {{end}}{{end}}'

英文:

I haven't used kubetcl before, but I am familiar with shell commands in general, from which I can tell you one thing that's going wrong, and maybe that's all you need. (I'm also somewhat familiar with Go templates, and your string comparison looks fine to me.) By using double quotes around your template and within your template, you're actually closing the string you're passing in as the template at the first double quote in "myapp". Using single quotes around the template should help:

kubectl get pods -o go-template --template='{{range .items}}{{if eq .metadata.labels.app "myapp"}}{{.metadata.name}} {{end}}{{end}}'

huangapple
  • 本文由 发表于 2017年9月15日 16:59:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/46235657.html
匿名

发表评论

匿名网友

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

确定