aminjam
aminjam

Reputation: 646

Golang template ignore if no match

I am trying to convert a golang template, and allow ignoring if the match is not found. Is that possible?

Playground

package main

import (
"bytes"
"fmt"
"text/template"
)
type Person struct {
Name string
Age  int
}
type Info struct {
Name string
Id   int
}

func main() {
msg := "Hello {{ .Id }} With name {{ .Name }}"
p := Person{Name: "John", Age: 24}
i := Info{Name: "none", Id: 5}

t := template.New("My template")
t, _ = t.Parse(msg)

buf := new(bytes.Buffer)
t.Execute(buf, p)
fmt.Println(buf.String())

buf = new(bytes.Buffer)
t.Execute(buf, i)
fmt.Println(buf.String())
}

I would like this to print

Hello {{ .Id }} with name John Hello 5 With name none

Upvotes: 3

Views: 4799

Answers (2)

miltonb
miltonb

Reputation: 7365

A template can contain if statements which allow you to do what you would need. The following example allows displaying a list if supplied, or when not supplied putting a message.

    {{if .MyList}}
      {{range .MyList}}
        {{.}}
      {{end}}
    {{else}}
      There is no list provided.
    {{end}}

Using this approach I think you can achieve what you need. But it might not be pretty as you want to leave the unprocessed {{.Id}} in place.

Upvotes: 0

elithrar
elithrar

Reputation: 24270

If you want it to print name only when it's not an empty string:

"Hello {{ .Id }} With name {{ if .Name }}{{ .Name }}{{ end }}"

Else, if you want to it print something else:

"Hello {{ .Id }} With name {{ if .Name }}{{ .Name }}{{ else }}none!{{ end }}"

Playground - also see the comparison operators for html/template and text/template.

Upvotes: 1

Related Questions