Prevent "<no value>" being inserted by golang text/template library
Asked Answered
S

3

7

Go places <no value> as the result of a the template expansion when no value is present for a particular template parameter.

Is there any way to prevent this? All I can think of right now is to insert an empty version of "AppVersion" into the data map

e.g.

package main

import (
    "text/template"
    "log"
    "bytes"
    "fmt"
)

func main() {
    data := make(map[string]string)
    //data["AppVersion"] = "Octane_3.0"

    text := "APP_VERSION={{.AppVersion}}"
    tmpl, err := template.New("").Parse(text)
    if err != nil {
        log.Fatal(err)
    }

    var b bytes.Buffer
    err = tmpl.Execute(&b, data)
    if err != nil {
        fmt.Println("template.Execute failed", err)
    }

    fmt.Println("Template text:", text)
    fmt.Println("Expanded:", b.String())
}

https://play.golang.org/p/OuLhcHOCsWJ

Subarid answered 20/4, 2018 at 3:49 Comment(0)
S
16

Ooops, found the answer if anyone interested I'll leave the question & answer up.

tmpl, err := template.New("").Option("missingkey=zero").Parse(text)
Subarid answered 20/4, 2018 at 3:53 Comment(1)
You can also specify missingkey=error if you want the templating to fail verbosely.Ewer
L
1

Another option is to test first with the ne function native to the templates. Check the value vs. nil. So changing your template to something like this should work..

text := `{{ if ne .AppVersion nil }}APP_VERSION={{.AppVersion}}{{ end }}`
Landsturm answered 12/10, 2021 at 0:7 Comment(1)
docs on how to do thisSora
P
0

You can use html/template instead of text/template to solve your problem.

Prepense answered 23/12, 2021 at 2:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.