How Can I Print a Period After the Last Item in a Go Template Range?

Susan Sarandon
Release: 2024-11-01 02:10:02
Original
715 people have browsed it

How Can I Print a Period After the Last Item in a Go Template Range?

Detecting the Last Item in an Array Using Ranges in Go Templates

In Go templates, when iterating over an array using the range directive, it can be difficult to avoid printing a trailing comma after the last item. This can lead to unexpected or incorrect output when rendering data as text.

Problem:

The following Go template outputs commas after each item in an array:

{{range $i, $el := .items}}{{$el}},{{end}}
Copy after login

The desired output, however, is to print a period after the last item:

1,4,2.
Copy after login

Solution:

To print a period after the last item in the array, the template can be modified as follows:

<code class="text">{{range $i, $el := .items}}{{if $i}},{{end}}{{$el}}{{end}}.</code>
Copy after login

The trick here is to use the conditional expression {{if $i}} to emit the comma separator before each item, except for the first one. By adding a period after the closing curly bracket of the range directive, the program ensures that a period is printed after the last item.

This updated template will iterate over the array and print each item with a comma separator, except for the first one. After the last item, a period will be printed instead of a comma.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!