dongliyan7318 2016-01-13 08:29
浏览 62
已采纳

在领事模板中的循环中覆盖变量

I'm using the following template in consul-template:

{{ range services }}
  {{ $server_name := .Name | replaceAll "_" "." }}
  {{ range .Tags }}
    {{ if . | regexMatch "server_name=" }}
      # found matching server_name in {{ . }}
      {{ $server_name := . | regexReplaceAll ".*=" "" }}
    {{ end }}
  {{ end }}
  # server_name = {{ $server_name }}
        acl host_{{ .Name }} hdr(host) -i {{ $server_name }}
        use_backend {{ .Name }}_backend if host_{{ .Name }}
{{ end }}

which produces

  # found matching server_name in server_name=geoserver.hello.org






  # server_name = geoserver.dev.hello.org
        acl host_geoserver_dev_hello_org hdr(host) -i geoserver.dev.hello.org
        use_backend geoserver_dev_hello_org_backend if host_geoserver_dev_hello_org

where .Name is geoserver_dev_hello_org and there is a server_name=geoserver.hello.org tag. I expect that by the end of the .Tags range loop, $server_name should have value geoserver.hello.org, but it still has its original value of geoserver.dev.hello.org.

How can I make it so that the loop overrides $server_name (and exit the loop when the value is found)?

  • 写回答

2条回答 默认 最新

  • dqz30992 2016-01-13 09:23
    关注

    Inner $server_name and outer $server_name are different variables. You can't set a variable from outer scope in Go templates: http://play.golang.org/p/0fuOmqXrSK.

    You could try and rewrite your template to print the acl etc. part inside the inner if which would work unless you need to execute that part just once. Go templates are not designed as a scripting language for complex logic, it's a tool for showing pre-computed information. A fmt.Printf on steroids if you will. All logic including search and replacement should be in Go, it'll be faster, safer, easier to maintain and debug.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?