jet
jet copied to clipboard
Working with *string Fields
I have a Struct like this
type Example struct {
SomeField *string
}
If I pass the Example struct to the data
for view.Execute
then in the template I have something like
{{ if .SomeField == "some_value" }} HAS SOME VALUE {{ end }}
The expression will always be False because the type of ".SomeField" is a *string
and the Right-hand side is string
so they are considered incompatible.
The "solution" was to add a Global function like this
views.AddGlobalFunc("nz", func(a jet.Arguments) reflect.Value {
// Helps convert the *string fields to just a string we can compare.
a.RequireNumOfArguments("nz", 1, 1)
val := a.Get(0)
if val.IsNil() {
return reflect.ValueOf("")
}
result := cast.ToString(val.Interface())
return reflect.ValueOf(result)
})
And use this ie
{{ if nz(.SomeField) == "somevalue") }}
And it now works as expected because the function will make sure it's a String
I have just started working with Jet, so Apologies if I have missed something. Thanks for all your work.