Go text/template templates: how to build a fallback when parent node in JSON input doesn't exist?

Viewed 38

Let's say you have a JSON input that normally comes into your system, like:

{ "foods": { "plants": { "fruit": "apple" } } }

But you want to be able to handle a case where the "plants" node doesn't exist or its value is null. Like:

{ "foods": { "plants": null } }

or

{ "foods": { "fungi": { "mushrooms": "button" } } }.

When I've tried doing various if statements and things (like {{ if .foods.plants.fruits }}stuff...{{ end }}, I keep running into errors like <.foods.plants.fruits>: map has no entry for key "plants" or <.foods.plants.fruits>: nil pointer evaluating interface {}.fruits

I want a template where, if the parent node does not exist, I can try checking a fallback option, without the Go panicking or the template refusing to continue executing. Like, say, have it use foods.fungi.mushrooms alternate node if the plants parent node doesn't exist.

Is this possible in Go text/templates? I scoured through the docs and did some googling but am not seeing anything obvious.

Thanks!

1 Answers

A coworker of mine suggested a solution that ended up working: use the built-in index function:

{{ if index .foods "plants" }}do stuff{{ else }}do other stuff when '.foods.plants' is missing{{ end }}

Related