text template and white space suppression

57 views
Skip to first unread message

Bill Nixon

unread,
Jun 28, 2020, 3:27:16 PM6/28/20
to golang-nuts
I am trying to do some creative formatting using text template and wanted to see if there might be a better approach than what I implemented.

I have an array of structs, where each element has a Project and Task. The array is sorted by Project.
type DisplayTask struct {
 
Project string
 
Task string
}

I want to output all the tasks within a project without repeating the project name each time and I want the tasks to be indented, for example:
Project1 
  Task1
  Task2
Project2 
  Task3
Project3 
  Task4
  Task5

After much experimentation, I am using the following template and trying to determine if there is a way to avoid the printf and just have the indent as part of the template, but I can't figure out a way to do this and suppress white space (newline) from the if statement for the same project.
{{- $lastProject := "" -}}
{{ range . }}
{{- if (ne $lastProject .Project) -}}
{{ .Project }} {{ $lastProject = .Project }}
{{ end -}}
 
{{ printf "  %s" .Task }}
{{ end -}}

Go Playground of the working code is at https://play.golang.org/p/3qqVW8lN-Ha

The challenge I had was suppressing white space after the end, but still allowing an indent via white space, so resorted to the printf.

Is there a better way?

go je

unread,
Jun 29, 2020, 12:26:10 PM6/29/20
to Bill Nixon, golang-nuts
Maybe templating engines help..
here's one example.


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/8da74f77-a462-4bdf-9491-38e403d8c250o%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages