Add commas between tags range

How do you write this function. I would love to put in a comma in between tags but not at the last tag item.
So say you have two tags = tag1,tag2.
if you have just one tag the comma shouldn’t come up.

I tried this but doesn’t work.

{{$num_tags = len .Params.tags}}
{{range .Params.tags}}
<a>{{.}}</a>{{if ge $num_tags 2}},{{end}}
{{end}}

See Howto: Delimiter separated tags

Thanks. That link doesn’t have anchor tags in between the tags

I think a pretty minor change to what bep showed would work:

{{ range $i, $e := .Params.tags }}{{ if $i }}, {{ end }}{{ printf "<a>%s</a>" $e }}{{ end }}

or something pretty similar should get the job done.

{{ delimit (apply .Params.tags "printf" "<a>%s</a>" ".") "," }}
1 Like

Thank you. I tried this and it only gives the output of the tags but the link doesn’t get attached.

Can we see an example of front matter?

@ddanawoski Not sure which of us you were replying to, but I think I figured out what you mean. I think both Joe and I were following your code to closely. What I think you’re looking for is this:

{{ range $i, $e := .Params.tags }}{{ if $i }}, {{ end }}{{ printf "<a href=\"/%s\">%s</a>" $e $e }}{{ end }}

except there is likely a better way to do the “/%s” and probably this could be done with delimit + apply, but I’ll let @jmooring handle that as I’m not used to the apply function, and he’s far better with Hugo than I am in any event.

We’ve been answering the wrong question.

With this front matter:

tags = ['tag-a','tag-b','tag-c']

@ddanawoski wants this:

<a href="/tags/tag-a/">tag-a</a>, 
<a href="/tags/tag-b/">tag-b</a>, 
<a href="/tags/tag-c/">tag-c</a>

They just didn’t know how to ask the question.

{{ range $k, $v := .GetTerms "tags" }}
  {{- if $k }}, {{ end }}
  <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{- end }}

https://gohugo.io/templates/taxonomy-templates/#example-list-tags-in-a-single-page-template

16 Likes

@jmooring : Thanks. That works flawlessly. Is there a doc where I can read extensively on range? Or is this a golang experience?

https://gohugo.io/templates/introduction/#iteration

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.