问题描述
如何连接使用 Go 模板的字符串中的变量?这是原始行(来自 https://github.com/nginx-proxy/nginx-proxy/blob/master/nginx.tmpl):
{{ $host := trim $host }}
{{ $is_regexp := hasPrefix "~" $host }}
{{ $upstream_name := when $is_regexp (sha1 $host) $host }}
{{ $access_log := (or (and (not $.Env.disABLE_ACCESS_LOGS) "access_log /var/log/Nginx/access.log vhost;") "") }}
我正在尝试在该字符串中使用变量“host”,如下所示:
{{ $host := trim $host }}
{{ $is_regexp := hasPrefix "~" $host }}
{{ $upstream_name := when $is_regexp (sha1 $host) $host }}
{{ $access_log := (or (and (not $.Env.disABLE_ACCESS_LOGS) "access_log /var/log/Nginx/" + $host + "_access.log vhost;") "") }}
但我收到此错误:
Unable to parse template: template: Nginx.tmpl:175: illegal number Syntax: "+"
解决方法
它使用 printf
{{ $host := trim $host }}
{{ $is_regexp := hasPrefix "~" $host }}
{{ $upstream_name := when $is_regexp (sha1 $host) $host }}
{{ $access_log := (or (and (not $.Env.DISABLE_ACCESS_LOGS) (printf "%s%s%s" "access_log /var/log/nginx/vhosts/" $host "_access.log vhost;")) "") }}