Check if context is string or dict

(I am open for other approaches to this, if there are any…)

I want to implement a partial that either receives a simple string or a dict as context. Is there any way to check a variable if it is a dict?

I am aware that I could do the following to check if it’s a string:

{{ if eq (printf "%s" .) . }}

but that won’t be telling me, that it’s a dict if it returns false (could be a float or boolean or even nil or whatever).

Is there any printf-parameter that I can use for a dict (array[ bla=fasel, something=somethingelse])? Or is there a completely different way to either have one single parameter or multiple parameters in a partial?

Try {{ printf "%T" . }} : fmt - The Go Programming Language

Hmm, that returns a map[string]interface {}. But a map can be a “one-dimensional” array too, right? I am not too versed with all that terminology.

Maybe it’s best to just check for a certain subvalue and if that is nil then assume whatever is in the context is a string?

I’m not sure what you mean?

If you just want to know if the input is type string or type NotAString, this is a quick way of doing it.

That’s what I mean, I want to tackle the issue from the other side: I want to know if it’s a dict or not, not if it’s a string or not. Finding out it’s a string is easy, but I want to make sure it’s a data structure that has keynames and values.

What I mean is if it’s not a string it could still be a float or integer or even nil, not a dict.

1 {{ printf "%T" "string input" }}
2 {{ printf "%T" (dict "key1" "dict" "key2" "input") }}
3 {{ printf "%T" (slice "this" "is" "an" "array") }}
4 {{ printf "%T" (slice "this" "is" 1 "array") }}
5 {{ printf "%T" (slice 1 2 3 4 ) }}
6 {{ printf "%T" 4 }}
7 {{ printf "%T" 4.4 }}
8 {{ printf "%T" nil }}
1 string
2 map[string]interface {}
3 []string
4 []interface {}
5 []int
6 int
7 float64
8 <nil>

So if the question is: type map or type NotAMap:

{{ $type :=  printf "%T" .  }}
{{ if in $type "map" }}is map
{{ else }}not map
{{ end }}

If you want it more granular, then you if-else through all the possibilities.


that makes sense and I get it :slight_smile: thanks.

You’ve also got reflect.IsMap and its brother reflect.IsSlice.


This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.