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 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单