Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Working with *string Fields #210

Open
ocomsoft opened this issue Dec 7, 2023 · 0 comments
Open

Working with *string Fields #210

ocomsoft opened this issue Dec 7, 2023 · 0 comments

Comments

@ocomsoft
Copy link

ocomsoft commented Dec 7, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant