Home  >  Article  >  Backend Development  >  How to Print a Period After the Last Array Item in a Go Template?

How to Print a Period After the Last Array Item in a Go Template?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 04:36:02502browse

How to Print a Period After the Last Array Item in a Go Template?

Detecting the Last Array Item in a Go Template

When iterating over an array in a Go template, a common problem is printing a comma after each element. This can be undesirable when displaying the last element, where a period would be a more suitable ending character.

In the provided code, the template {{range $i, $el := .items}}{{$el}},{{end}} iterates over the items array and prints each element followed by a comma. To print a period after the last element, we need to modify the template.

The solution involves using the if statement to conditionally include the comma. Here's the modified template:

<code class="go">tpl := "{{range $i, $el := .items}}{{if $i}},{{end}}{{$el}}{{end}}."</code>

In this template:

  • The {{range $i, $el := .items}} part remains the same.
  • We add an if $i statement that checks if $i is greater than zero. This condition is true for all elements except the first one.
  • If $i is greater than zero, we print a comma.
  • We print {{$el}} to output the element.
  • We end the range with {{end}}.
  • We append a period character at the end of the template.

With this template, the program will print the following:

1,4,2.

The last element is correctly ended with a period. This technique of conditionally printing separators is a useful trick for formatting output in Go templates.

The above is the detailed content of How to Print a Period After the Last Array Item in a Go Template?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn