-2

How can I concatenate a variable in a string that is used a Go template? This is the original line (from 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;") "") }}

I am trying to use variable "host" in that string like this:

{{ $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;") "") }}

But I get this error:

Unable to parse template: template: nginx.tmpl:175: illegal number syntax: "+"
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
brgsousa
  • 333
  • 1
  • 7
  • 20
  • 1
    Does this answer your question? [Is there an efficient way to concatenate strings](https://stackoverflow.com/questions/45389802/is-there-an-efficient-way-to-concatenate-strings) – Jonathan Hall Jan 27 '21 at 20:13
  • Unfortunately no , I can't create a function inside a template: Unable to parse template: template: nginx.tmpl:175: function "func" not defined – brgsousa Jan 27 '21 at 21:29
  • I am thinking I will have to edit this https://github.com/jwilder/docker-gen/blob/master/template.go and recompile this project so I can use the function strings.Join() – brgsousa Jan 27 '21 at 21:43
  • 1
    `strings.Join` isn't the only option provided in the duplicate. – Jonathan Hall Jan 28 '21 at 08:21
  • Thanks! printf worked – brgsousa Jan 28 '21 at 14:33

1 Answers1

0

It works making use of 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;")) "") }}
brgsousa
  • 333
  • 1
  • 7
  • 20